Repository navigation
Studio: cancel an in-flight generation on safetensors/MLX model switch - #6783
danielhanchen wants to merge 21 commits into
Conversation
|
@codex review |
There was a problem hiding this comment.
Code Review
This pull request improves the model unloading process in the inference orchestrator by cancelling any active generation and acquiring the generation lock before unloading, preventing the UI from hanging during long generations. It also introduces a fallback timeout that shuts down the subprocess if the worker is wedged, and includes comprehensive unit tests. However, a critical deadlock risk was identified where a thread from a cancelled generation could persist and block on the response queue of a newly spawned subprocess. To resolve this, it is recommended to update the token stream consumption logic to exit if the subprocess or response queue instances change.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
| acquired = self._gen_lock.acquire(timeout = _UNLOAD_GEN_LOCK_TIMEOUT) | ||
| if not acquired: | ||
| # Wedged worker: tear the subprocess down to free the GPU; the next | ||
| # load spawns a fresh one. | ||
| logger.warning( | ||
| "Unload: generation did not yield %.1fs after cancel; " | ||
| "shutting the inference subprocess down to free the model", | ||
| _UNLOAD_GEN_LOCK_TIMEOUT, | ||
| ) | ||
| self._shutdown_subprocess(timeout = 5) | ||
| self.models.pop(model_name, None) | ||
| if self.active_model_name == model_name: | ||
| self.active_model_name = None | ||
| return True |
There was a problem hiding this comment.
Critical Deadlock / Livelock Risk
When a worker is wedged, the active generation thread (Thread A) is holding _gen_lock and is blocked inside _consume_token_stream on self._read_resp (waiting on self._resp_queue).
If unload_model times out after 15 seconds, it executes this fallback block:
- It calls
self._shutdown_subprocess(timeout=5), which kills the old process and setsself._proc = Noneandself._resp_queue = None. - It returns
True, allowing the orchestrator to proceed. - A subsequent
load_modelcall spawns a fresh subprocess, overwritingself._procandself._resp_queuewith the new active instances.
Meanwhile, Thread A wakes up from self._read_resp (since the old queue was cleared), but then checks self._ensure_subprocess_alive(). Because self._proc has been overwritten with the new alive subprocess, self._ensure_subprocess_alive() returns True! Thread A then continues its loop and blocks on self._read_resp again, which now reads from the new self._resp_queue.
This creates a permanent deadlock:
- Any new generation request will block on
_gen_lock(still held by Thread A). - Since the new generation cannot start, nothing is written to the new queue, causing Thread A to block forever on the new queue.
Solution
To prevent this, _consume_token_stream should capture the initial process and queue instances before entering its loop, and exit immediately if either has changed. Since _consume_token_stream is not in the diff, you can update it as follows:
def _consume_token_stream(
self,
read_one,
drain_on_cancel,
*,
crash_context: str,
cancel_event = None,
stats_holder: Optional[dict] = None,
read_timeout: float = 30.0,
) -> Generator[str, None, None]:
initial_proc = self._proc
initial_resp_queue = self._resp_queue
while True:
if self._proc is not initial_proc or self._resp_queue is not initial_resp_queue:
yield f"Error: {self._subprocess_crash_message(crash_context)}"
return
resp = read_one(read_timeout)
...There was a problem hiding this comment.
The guard is in place at head. _consume_token_stream latches initial_proc and initial_resp_queue before the loop and bails with the subprocess-crash message if either identity changes, so a still-live generation thread cannot re-block on a freshly spawned queue while holding _gen_lock. Covered by test_consume_token_stream_bails_when_subprocess_swapped in test_orchestrator_unload_cancel.py.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6a0fa66eb7
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| # token), then take _gen_lock to be the sole resp_queue reader, matching | ||
| # the GGUF backend which cancels and kills its process on unload. | ||
| self._cancel_generation() | ||
| acquired = self._gen_lock.acquire(timeout = _UNLOAD_GEN_LOCK_TIMEOUT) |
There was a problem hiding this comment.
Avoid waiting on the stream lock on the event loop
When /unload (or the GGUF /load path that unloads the Unsloth backend) calls this synchronous method from the async route, an active streaming response can be paused after yielding a token while still holding _gen_lock; the stream task only schedules the next next(gen) call from the event loop, which is now blocked here waiting for the same lock. In that common slow-client/interleaving case the cancel event is set but the parent stream cannot consume gen_done and release the lock, so model switching stalls until _UNLOAD_GEN_LOCK_TIMEOUT and then kills the subprocess instead of completing near-instantly.
Useful? React with 👍 / 👎.
| # Drop stale tokens from the cancelled generation so they can't be | ||
| # read as the unload reply. | ||
| self._drain_queue() | ||
| self._send_cmd( |
There was a problem hiding this comment.
Prevent queued generations from overtaking unload
When another non-adapter generation is already waiting on _gen_lock, the unload request cancels the current stream but does not enqueue the unload command until after it wins this lock. After the current stream exits, that waiting generation can acquire _gen_lock first, send a new generate command that the worker clears the cancel event for, and start running on the old model ahead of the model switch; before this change, unload was queued immediately so later generations stayed behind it in the subprocess command queue.
Useful? React with 👍 / 👎.
| } | ||
| ) | ||
| resp = self._wait_response("unloaded") | ||
| self._wait_response("unloaded") |
There was a problem hiding this comment.
Stop the dispatcher before waiting for unload
When an adapter/compare-mode generation is active, _generate_dispatched leaves the dispatcher thread reading the shared resp_queue, but this unload path waits for unloaded by reading that same queue directly. The dispatcher drops responses without a matching request_id, so it can consume the worker's unloaded reply before _wait_response sees it, making model switching during compare mode hang until the 300s inactivity timeout even though the worker already processed the unload.
Useful? React with 👍 / 👎.
Switching models while a safetensors or MLX generation was running hung the UI for the whole generation (2-3 min for a long reasoning answer). The orchestrator subprocess processes commands sequentially, so a bare "unload" queued behind the running "generate" and waited it out. The GGUF backend already avoids this by cancelling and killing its process on unload. InferenceOrchestrator.unload_model now mirrors that: it cancels the in-flight generation first (the mp.Event the worker checks each token, so the abort lands within a token, ~0.1s) and then takes _gen_lock before the unload round-trip, so it is the sole resp_queue reader. A bounded wait falls back to tearing the subprocess down if a wedged worker never yields the lock, so the GPU is freed regardless. MLX shares the same worker/orchestrator, so it is covered too. Measured on the running Studio: unload during a live generation dropped from ~2.5 min to 0.53 s. Adds tests/test_orchestrator_unload_cancel.py (cancel-before -unload ordering, no-generation path, and the wedged-worker shutdown fallback).
6a0fa66 to
bf21d69
Compare
|
Real deadlock, fixed in bf21d69. |
Follow-ups to the cancel-before-unload change: - Stop the compare-mode dispatcher (via _wait_dispatcher_idle) before reading the unload reply, so it cannot consume the worker's "unloaded" response off the shared resp_queue and stall the switch until the inactivity timeout. - Add an _unload_pending flag set across the switch: a generation that wins the _gen_lock handoff bails instead of starting on the outgoing model, so a queued request cannot overtake the unload. Cleared on every unload exit path. - Route: run the safetensors unload off the event loop (asyncio.to_thread) at the /unload route and the GGUF-load pre-unload, so a slow SSE stream paused between tokens (still holding _gen_lock) does not block the loop that drives its next token and the lock release. Tests for the pending-flag clear and the queued-generation bail.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b5a9198c1e
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if self._unload_pending: | ||
| # A model switch won the lock handoff; do not start a new | ||
| # generation on the outgoing model. | ||
| yield "Error: model is being unloaded" |
There was a problem hiding this comment.
Apply unload-pending guard to every generation path
This guard only protects the locked text path. While unload is waiting for _gen_lock after setting _unload_pending, a compare-mode request (payload.use_adapter -> generate_with_adapter_control, which bypasses _gen_lock) or an audio-input request (takes _gen_lock but has no pending-unload check) can still enqueue a new generate/generate_audio_input before unload_model sends its unload command; the worker clears the shared cancel event when it starts that command, so the request runs on the outgoing model and delays the switch. Please gate the dispatched/audio generation paths on _unload_pending as well, or otherwise ensure unload is queued ahead of them.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 82d5383. Both non-locked paths now bail when _unload_pending is set: _generate_dispatched (compare mode) early-outs before starting the dispatcher or sending the command, and _generate_audio_input_inner checks it inside _gen_lock like the text path. Added test_dispatched_generation_bails_when_unload_pending and test_audio_input_generation_bails_when_unload_pending.
|
Addressed the three concurrency notes in b5a9198:
Tests added for the pending-flag clear and the queued-generation bail. |
e933ae3 to
e7c786c
Compare
The _unload_pending switch guard only protected the locked text path. A compare-mode request (generate_with_adapter_control -> _generate_dispatched, which bypasses _gen_lock) or an audio-input request could still enqueue a generate on the outgoing model while unload waited for _gen_lock, clearing the worker cancel event and delaying the model switch. Add the same bail on both paths so unload stays ahead of them.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 82d5383eec
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| ) | ||
| resp = self._wait_response("unloaded") | ||
| self._cancel_generation() | ||
| acquired = self._gen_lock.acquire(timeout = _UNLOAD_GEN_LOCK_TIMEOUT) |
There was a problem hiding this comment.
Gate TTS generation during pending unload
When an unload starts during a locked text stream, this line can leave _unload_pending true for up to _UNLOAD_GEN_LOCK_TIMEOUT before the unload command is actually queued, but generate_audio_response still bypasses _gen_lock and has no pending-unload check. A concurrent /audio/generate request from routes/inference.py can therefore enqueue generate_audio ahead of the unload; the worker clears cancel_event for that command, so the outgoing model keeps running TTS and the unload waits or competes for the same resp_queue. Please gate or serialize the TTS path the same way as the other generation paths.
Useful? React with 👍 / 👎.
| "shutting the inference subprocess down to free the model", | ||
| _UNLOAD_GEN_LOCK_TIMEOUT, | ||
| ) | ||
| self._shutdown_subprocess(timeout = 5) |
There was a problem hiding this comment.
Do not return while the stream still owns the lock
When the lock holder is an SSE stream paused after yielding a token, this timeout branch can run even though that generator still owns _gen_lock; _shutdown_subprocess() kills the worker but cannot release a lock held by the streaming thread, and unload_model then returns success and clears _unload_pending. Fresh evidence here is that this branch returns without ever acquiring/releasing _gen_lock. After a new model is loaded, normal text/audio-input generations block on the stale lock until the slow client resumes or disconnects, so one slow stream can wedge the backend past the model switch.
Useful? React with 👍 / 👎.
generate_audio_response (TTS) was the only generation path that neither took _gen_lock nor checked _unload_pending, so a concurrent /audio/generate could start TTS on a model being switched out. Serialize it under _gen_lock and refuse to start once an unload is pending (raising, since the call is blocking), matching the text and audio-input paths. Add a regression test.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cd16c2e165
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if self._unload_pending: | ||
| yield "Error: model is being unloaded" | ||
| return |
There was a problem hiding this comment.
Make compare unload guard atomic
When a compare-mode request passes this check just before an unload sets _unload_pending, the unload path can enter _wait_dispatcher_idle(), see no mailboxes, stop the dispatcher, and queue unload; the request then registers a mailbox and sends generate but no dispatcher is left to deliver gen_done/gen_error, so that SSE waits indefinitely while the worker replies on resp_queue. The fresh evidence is that the guard is outside any synchronization and runs before mailbox registration; please serialize the guard/registration/send with unload.
Useful? React with 👍 / 👎.
| if self._unload_pending: | ||
| # Won the lock handoff during a switch; don't start on the outgoing model. | ||
| yield "Error: model is being unloaded" |
There was a problem hiding this comment.
Recheck unload state before enqueueing generate
If /unload starts after this guard passes but before _send_cmd, it sets _unload_pending and calls _cancel_generation() while blocked on _gen_lock; the worker then clears that cancel event when it handles the just-enqueued generate command, so a fresh request can run on the outgoing model and force the switch into the 15s timeout/shutdown path. This is a separate race from queued waiters because the request has already passed the new guard; make the guard and enqueue atomic with unload, or cancel again after unload acquires the lock.
Useful? React with 👍 / 👎.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cd16c2e165
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| self._cancel_generation() | ||
| acquired = self._gen_lock.acquire(timeout = _UNLOAD_GEN_LOCK_TIMEOUT) |
There was a problem hiding this comment.
Prevent queued compare requests from outliving unload
When compare mode has more than one dispatched request already queued, this cancel only affects the request currently running in the worker; the next queued generate will later execute cancel_event.clear() in the worker command loop before starting, so it runs to completion while _wait_dispatcher_idle() waits and the model switch/unload can still stall. This affects adapter-controlled/compare requests that were enqueued just before the unload began; the new _unload_pending check only blocks future enqueues, not commands already sitting in the subprocess queue.
Useful? React with 👍 / 👎.
|
@codex review |
|
Codex Review: Didn't find any major issues. Another round soon, please! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cd16c2e165
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| try: | ||
| # Stop the compare-mode dispatcher so it can't consume the | ||
| # "unloaded" reply off the shared resp_queue before we read it. | ||
| self._wait_dispatcher_idle() |
There was a problem hiding this comment.
Handle active dispatched generations before queuing unload
When a compare-mode generation is still active, it bypasses _gen_lock, so this acquire succeeds immediately and _wait_dispatcher_idle() can return after its idle timeout with mailboxes still present and the dispatcher still reading resp_queue. In that state the unload command is queued behind the still-running generation, and the dispatcher can also consume/drop the eventual unloaded reply, so switching models during a stuck or slow compare-mode request can still hang for the full wait timeout (or report unloaded locally while the worker kept the model). Treat the still-active dispatcher case like the wedged locked-generation path instead of proceeding to _wait_response.
Useful? React with 👍 / 👎.
…load A compare-mode (dispatched) generation bypasses _gen_lock, so a wedged one (stuck emitting no tokens) slips past the acquire guard in unload_model. In that state _wait_dispatcher_idle times out and leaves the dispatcher running, and the code proceeded to _drain_queue/_send_cmd/_wait_response anyway. The still-running dispatcher owns resp_queue and drops the request_id-less 'unloaded' reply, so _wait_response blocks for its full timeout and can then report the unload failed even though the worker eventually unloaded, hanging a model switch for up to five minutes. Make _wait_dispatcher_idle return whether it stopped the dispatcher, and when it did not (compare mailboxes still active), tear the subprocess down to free the GPU, mirroring the existing wedged locked-generation path. A fresh load spawns a new subprocess. Add a regression test.
# Conflicts: # studio/backend/routes/inference.py
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cd7eaf39a2
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| # consume and drop each other's token events. Hold _gen_lock across the | ||
| # cmd build + send + whole stream so we stay the sole resp_queue reader. | ||
| with self._gen_lock: | ||
| if self._unload_pending: |
There was a problem hiding this comment.
Recheck model state after waiting for _gen_lock
This guard only rejects requests that acquire _gen_lock while _unload_pending is still true. If a second text generation had already passed the outer active_model_name check and was blocked behind another generation before unload started, unload_model can acquire the lock first, unload, clear _unload_pending, and then this waiter proceeds without revalidating the active model/subprocess; if a new load has completed, the stale request can be sent to the new model, otherwise it is enqueued against an unloaded worker. Please re-check the active model or a generation epoch under the lock before sending the command.
Useful? React with 👍 / 👎.
| # unload sits behind the stuck generate, hanging _wait_response for | ||
| # its full timeout. Mirror the wedged locked-generation path: tear | ||
| # the subprocess down to free the GPU; the next load spawns fresh. | ||
| if not self._wait_dispatcher_idle(): |
There was a problem hiding this comment.
Prevent queued compare requests from outliving unload
When compare/adapter mode already has more than one dispatched request queued, the single _cancel_generation() above only cancels the command currently running in the worker; the worker clears the same event whenever it dequeues the next generate, so a queued compare request can start on the outgoing model while this call waits for _wait_dispatcher_idle() to time out or for that request to finish. In that scenario a model switch can still stall for the full compare response or 30s before teardown, so unload should either drain/refuse queued dispatched commands or tear down as soon as active mailboxes remain after cancellation.
Useful? React with 👍 / 👎.
| # A model switch is in flight (unload waiting on _gen_lock). This path | ||
| # bypasses _gen_lock, so without this early-out a compare-mode request | ||
| # would enqueue a generate on the outgoing model and delay the switch. | ||
| if self._unload_pending: |
There was a problem hiding this comment.
Synchronize compare generation with unload start
This _unload_pending check is not synchronized with the later mailbox registration or command send. If a compare request passes this line just before unload_model sets _unload_pending, unload can see no mailboxes, stop the dispatcher, and enqueue unload; the compare request can then add a mailbox and enqueue generate with no dispatcher left to route its response, or enqueue ahead of unload and run on the outgoing model. Please guard the check/mailbox registration/send with the same state transition used by unload so no dispatched request can slip through mid-switch.
Useful? React with 👍 / 👎.
| initial_proc = self._proc | ||
| initial_resp_queue = self._resp_queue | ||
| while True: | ||
| if self._proc is not initial_proc or self._resp_queue is not initial_resp_queue: |
There was a problem hiding this comment.
Avoid reading the new subprocess queue from an old stream
This identity check runs before read_one, but the locked text/audio paths pass self._read_resp, which dereferences self._resp_queue when it is called. If a reload swaps _resp_queue immediately after this check, the old stream can block on or consume responses from the new subprocess while still holding _gen_lock -- for example stealing the new load's loaded response and making the load time out. The reader should use the captured queue/proc or re-check after selecting the queue, rather than calling back through mutable orchestrator state.
Useful? React with 👍 / 👎.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cd7eaf39a2
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if self._unload_pending: | ||
| yield "Error: model is being unloaded" | ||
| return |
There was a problem hiding this comment.
Guard compare generation atomically during unload
When a compare-mode request has just passed this _unload_pending check but its queued generate has not yet been picked up by the worker, a concurrent unload can set _unload_pending and the shared cancel event; the worker then clears that event when it starts the queued generate (worker.py:920-922), so the unload's cancel is lost. Because this dispatched path bypasses _gen_lock, the unload can wait until _DISPATCH_IDLE_TIMEOUT or until the full generation finishes before tearing down, reintroducing the switch delay this change is meant to avoid. The check and enqueue need to be serialized with unload, or rechecked under a shared lock, so no dispatched generate can be queued once unload begins.
Useful? React with 👍 / 👎.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: cd7eaf39a2
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if self._unload_pending: | ||
| # Won the lock handoff during a switch; don't start on the outgoing model. | ||
| yield "Error: model is being unloaded" | ||
| return |
There was a problem hiding this comment.
Recheck model state after waiting for unload
When a request has already passed the earlier active_model_name check but is blocked on _gen_lock, a concurrent unload can acquire the lock first, unload the worker, set active_model_name = None, and then clear _unload_pending. That waiter then reaches this block with _unload_pending == False and proceeds to enqueue a generate command against an unloaded subprocess; recheck the active model under the lock or keep a switch epoch so stale waiters bail after the unload completes.
Useful? React with 👍 / 👎.
| if self._unload_pending: | ||
| yield "Error: model is being unloaded" | ||
| return |
There was a problem hiding this comment.
Close the compare-mode unload race
For compare-mode requests that start at the same time as /unload, this check can pass just before unload_model sets _unload_pending; because this path bypasses _gen_lock, it will still create a mailbox and enqueue generate while unload is waiting in _wait_dispatcher_idle. The worker clears cancel_event when it starts each queued generate, so the unload-side cancel can be lost and the switch waits until the dispatcher idle timeout before killing the subprocess; recheck under shared synchronization or use an unload epoch immediately before _send_cmd.
Useful? React with 👍 / 👎.
| if resp is None: | ||
| if not self._ensure_subprocess_alive(): | ||
| raise RuntimeError(self._subprocess_crash_message("audio generation")) | ||
| continue |
There was a problem hiding this comment.
Latch TTS waits to the original subprocess
When /unload hits the timeout while a TTS request is running, the worker's generate_audio path does not poll the cancel event, so unload kills the subprocess and a subsequent load can install a new _proc/_resp_queue before this loop observes the old worker died. Unlike _consume_token_stream, this audio wait then treats the new subprocess as alive and continues reading the new response queue while still holding _gen_lock, which can steal the load response or block later generations; capture the initial process/queue here and abort if they change.
Useful? React with 👍 / 👎.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 347821fc7f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| self._shutdown_subprocess(timeout = 0.5) | ||
| self.loading_models.discard(target) |
There was a problem hiding this comment.
Cancel loads before waiting on shutdown
In cancel_load, the loading marker remains set while _shutdown_subprocess() runs. When /unload lands before a child exists (for example during GPU placement) or between retry attempts, load_model can reach its new pre-spawn if model_name not in self.loading_models check while this call is still in progress, still see the marker, and spawn a worker after the route has reported the load cancelled. Clear the marker before shutdown or protect the marker check/cancel with a lock.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 7bebc59. cancel_load runs off the lifecycle gate, concurrently with a load_model that rechecks the loading marker before each spawn, but it discarded the marker only after _shutdown_subprocess. That teardown can block for up to a second tearing a live child down or joining the compare dispatcher, so a racing load_model can read the marker still set during that window, pass its pre-spawn recheck, and spawn plus load the model after /unload already returned unloaded, leaving an orphaned worker on the GPU. This is a materially larger window than the load_model-internal gap at the spawn site I left as is earlier (that residual is a single logger.info plus a dict assign, no blocking call). The fix discards the marker and clears active_model_name and models before the teardown, so the recheck observes the cancel as soon as it is committed. Regression test test_cancel_load_clears_marker_before_shutdown asserts the marker is already cleared when _shutdown_subprocess is invoked; it fails on the old ordering and passes now.
| if unloading: | ||
| yield "Error: model is being unloaded" | ||
| return |
There was a problem hiding this comment.
Stop dispatcher when bailing during unload
When a compare-mode request races an unload, it can pass the early _unload_pending check, start the dispatcher, and then hit this unloading bail because the unload has already set _unload_pending. If the unload's _wait_dispatcher_idle() already returned while no dispatcher existed, this leaves a live dispatcher with no mailboxes; that dispatcher can consume and drop the subsequent unloaded response from resp_queue, so unload_model() waits until its 300s timeout. Stop the just-started dispatcher (when no mailbox was registered) before returning here.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed in 7bebc59. A compare request can pass the pre-work _unload_pending check, start the dispatcher (none was running), then bail under _mailbox_lock when a racing unload has since set _unload_pending. If that unload already passed its own _wait_dispatcher_idle while the dispatcher was still stopped (it returns True immediately when the thread is None, without reading _mailboxes), the just-started dispatcher is left alive with no mailboxes. It then races the _wait_response in unload_model for the worker unloaded reply off the shared resp_queue and, when it wins, drops it as unroutable, so the unload hangs until its 300s inactivity timeout. The dispatcher_alive recheck did not cover this: the dispatcher is alive here because this request started it, and the bail fires on _unload_pending, not on a dead dispatcher. The fix records whether the dispatcher pre-existed this call and, on the unloading bail, stops the dispatcher this call started when no other compare request holds a mailbox, so the unload stays the sole resp_queue reader. Regression test test_dispatched_bail_stops_orphan_dispatcher_it_started (fails without the fix), plus guards test_dispatched_bail_keeps_dispatcher_with_other_active_mailbox and test_dispatched_bail_keeps_preexisting_dispatcher against over-stopping.
| if _drain_skip_generate(cmd, resp_queue, drain_event): | ||
| continue |
There was a problem hiding this comment.
Drain queued audio commands during unload
The new unload drain only skips generate commands, but audio/TTS requests can also be queued behind an active compare-mode generation because compare mode bypasses _gen_lock. In that case /unload sets drain_event and cancel_event, but the queued generate_audio or generate_audio_input command later clears the cancel and runs on the outgoing model, so the switch waits for the 15s forced-shutdown path (or the audio completion) instead of aborting promptly. Apply the same durable drain handling to queued audio commands, with the appropriate terminal response for their callers.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Traced this but leaving it as is. The audio paths take _gen_lock: generate_audio_response and _generate_audio_input_inner both send under it. So a generate_audio queued behind a compare-mode generation during an unload is bounded. unload_model sets drain and cancel, then does _gen_lock.acquire(timeout=_UNLOAD_GEN_LOCK_TIMEOUT), which is 15s, and on timeout tears the subprocess down via _shutdown_subprocess. The queued audio holds _gen_lock while it runs on the outgoing model, so it delays the switch by at most that 15s and is then force-killed together with the worker; the switch always completes and the outgoing model is freed. There is no unbounded hang, no wrong persistent state, and no data loss beyond the audio request the user aborted by switching. Unlike a queued text generate, which the drain skips because it must not run on the outgoing model, the audio result is delivered to the caller that requested it on that model, so it is not a wrong later result. The undrained command is cleaned up by the already-enforced forced-shutdown fallback, which makes this bounded-latency hardening rather than a correctness bug. The deeper audio-with-compare-mode interaction (audio_done can be consumed by the live dispatcher and dropped) is pre-existing and orthogonal to the unload drain.
…uring unload cancel_load ran off the lifecycle gate but discarded its loading marker only after _shutdown_subprocess, which can block while tearing a live child down or joining the compare dispatcher. A racing load_model could read the marker still set during that window, pass its pre-spawn recheck, and spawn plus load the model after /unload already reported it cancelled. Discard the marker and clear local state before the teardown so the recheck observes the cancel as soon as it is committed. A compare request could also pass its pre-work unload check, start the dispatcher, then bail under _mailbox_lock when a racing unload set _unload_pending. If that unload had already passed its own _wait_dispatcher_idle while no dispatcher existed, the just-started dispatcher was left running with no mailboxes, raced unload_model's _wait_response for the worker unloaded reply, and dropped it as unroutable, hanging the unload until its 300s timeout. On the bail, stop the dispatcher this call started when no other compare request is using it, so the unload stays the sole resp_queue reader.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 7bebc5917e
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| self.loading_models.discard(target) | ||
| self.active_model_name = None | ||
| self.models.clear() | ||
| self._shutdown_subprocess(timeout = 0.5) |
There was a problem hiding this comment.
Recheck cancellation after a load completes
When Stop loading races with a worker that has already enqueued its loaded response, cancel_load() clears loading_models and local state before _shutdown_subprocess(), but the still-running load_model() thread can consume that loaded response immediately afterward and repopulate active_model_name/models while cancel_load() continues to kill the subprocess. Because _shutdown_subprocess() does not clear those mirrors afterward, /unload can report success but leave the backend advertising a loaded model whose worker was just torn down; add a post-response cancellation check in load_model() or clear state again after the shutdown.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed and fixed. The off-gate cancel_load can race a load_model parked in _wait_response for the loaded reply: cancel_load discards the marker and clears active_model_name and models before the teardown, but the loading thread can consume the worker's already-queued loaded during the shutdown settle window and repopulate the mirrors, which _shutdown_subprocess never touches, so unload reported success while the backend still advertised a model whose worker was just killed. Fixed by re-clearing active_model_name and models after _shutdown_subprocess in cancel_load; once the response queue is nulled no further loaded can be read, so the second clear wipes any repopulation the racing load committed during the window and leaves the backend advertising nothing loaded. Added a regression test that parks a load_model in _wait_response, releases the loaded reply inside cancel_load's teardown so the load repopulates the mirrors, then asserts they are empty after cancel_load returns; it fails without the second clear and passes with it.
cancel_load runs off the lifecycle gate, concurrently with a load_model whose worker may have already queued its successful loaded reply. cancel_load clears the loading marker and the local mirrors, then tears the subprocess down, but the still-running load_model thread can consume that loaded response during the teardown window (the 0.5s cancel settle before the response queue is drained and nulled) and repopulate active_model_name/models. _shutdown_subprocess nulls the queues but never touches those mirrors, so /unload reported success while the backend kept advertising a model whose worker was just killed. Clear the mirrors again after the teardown. Once the response queue is nulled no further loaded can be read, so the second clear wipes any repopulation the racing load committed during the window and leaves the backend advertising nothing. Adds a regression test that parks a load_model in _wait_response, releases the loaded reply inside cancel_load's teardown so the load repopulates the mirrors, and asserts they are empty after cancel_load returns.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 96183f665a
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| # between retry attempts) there is nothing to kill, and without this | ||
| # check the loop would spawn a fresh worker and load the model after | ||
| # /unload already reported it unloaded. Observe the removal and stop. | ||
| if model_name not in self.loading_models: |
There was a problem hiding this comment.
Recheck the loading marker after spawning
When the user clicks stop-loading during this gap, cancel_load() now runs off the lifecycle gate and can remove model_name from loading_models just after this pre-spawn check but while _spawn_subprocess() is still creating queues/the process. In that window _shutdown_subprocess() can no-op because _proc is still None or not alive, after which this load continues into _wait_response("loaded") and publishes the model even though /unload already returned unloaded. Recheck the marker immediately after spawning (and tear down the child if it was cleared), or make spawn/cancel atomic.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Good catch, fixed in 4f77775. The pre-spawn recheck only closes the window before any child exists. A cancel that lands after that recheck but while _spawn_subprocess is still creating the queues and the process is missed, because cancel_load runs off the lifecycle gate and its _shutdown_subprocess sees _proc not yet alive and no-ops, so nothing tears the worker down and the load goes on to wait for loaded and publish a model that /unload already reported as unloaded, with a live subprocess nothing later reaps. I added a second marker recheck immediately after _spawn_subprocess that tears the just-spawned worker down and returns False when the load was cancelled during the spawn window. Regression test test_load_model_aborts_when_cancelled_during_spawn covers it: it fails without the recheck by reaching _wait_response, and passes with it.
| "type": "gen_done", | ||
| "request_id": request_id, | ||
| "cancelled": True, | ||
| "stats": None, |
There was a problem hiding this comment.
Propagate drained generations as cancellations
When an unload starts while compare-mode has a generate already queued behind another request, this emits a normal gen_done; _consume_token_stream() treats gen_done as successful completion and ignores the cancelled flag, so the caller can receive a successful empty response rather than a cancellation/error for that skipped request. Emit a request error or have the parent handle cancelled gen_done explicitly so aborted compare/API requests are not recorded as valid empty generations.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. The queued generate is correctly skipped here, so the cancel is applied and the outgoing model never runs, which is the whole point of drain_event. The empty gen_done it emits matches how the actively cancelled in-flight generate is already reported: _handle_generate breaks on the cancel event and also emits a plain gen_done with no cancelled flag, and _consume_token_stream ends that stream as a completion too. So special casing only the queued request would leave the two cancellation paths inconsistent while still reporting the in-flight one as completed. There is no dropped or misapplied cancel, no hang, no leaked subprocess, no data loss, and later requests are unaffected, so this is a status or UX nuance rather than a correctness bug. Leaving as is.
| self.active_model_name = None | ||
| self.models.clear() |
There was a problem hiding this comment.
Avoid clearing a later load after cancel shutdown
Because cancel_load() runs off the lifecycle gate, the cancelled /load can release the gate while this thread is still inside _shutdown_subprocess(), allowing a subsequent /load for a different model to complete and set active_model_name/models before these unconditional clears run. In that race, stopping load A erases the freshly loaded model B's parent-side state even though its worker is alive, so status and generation report no model; clear only if the state still belongs to the cancelled target/subprocess or serialize this final cleanup with new loads.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
I do not think this over-clears a legitimate later load. load_model runs under the lifecycle gate, a process-wide threading.Lock held for the entire load, while cancel_load runs off-gate. A later load for a different model can only start once the cancelled load releases that gate, and it can only set active_model_name after its own worker finishes spawning and replies loaded, which is seconds of work at minimum. The second clear runs in the two statements right after _shutdown_subprocess returns, and _shutdown_subprocess here blocks only about a second (the 0.5s cancel settle plus the join, with no compare dispatcher during a load). A full spawn and load of another model cannot complete inside that window, so at this line active_model_name is only ever None or the racing same-load repopulation this clear is meant to wipe, never a freshly committed different model. The clear is bounded in time by the gate, not by target name, so scoping it to the cancelled target is not needed.
| self.loading_models.discard(target) | ||
| self.active_model_name = None | ||
| self.models.clear() | ||
| self._shutdown_subprocess(timeout = 0.5) |
There was a problem hiding this comment.
Avoid killing the previous model when cancelling a pending load
When switching from an active model A to model B, load_model() adds B to loading_models before it reaches the block that shuts down A; if the user hits Stop Loading during GPU placement or other pre-spawn work, this new off-gate cancel_load(B) path tears down self._proc, which is still serving A, and clears the active-model mirrors. In that timing, cancelling the not-yet-started load for B unexpectedly unloads the currently usable model A; only terminate the subprocess once it is known to belong to the cancelled load, or just remove B's loading marker before spawn.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Re-checked against the current code and the earlier reasoning still holds. A switch from A to B tears A down unconditionally in the block just before the spawn loop, and that block runs before the pre-spawn marker recheck, so load_model never consults the cancel before killing A. A is therefore already doomed the moment the switch starts, independent of any cancel. cancel_load tearing self._proc down in the pre-spawn window is redundant with that same teardown a moment later: with or without the cancel, load_model returns from prepare_gpu_selection, hits that block, kills the live A, and then bails at the recheck with nothing loaded. There is no interleaving where cancel_load kills A but load_model would have preserved it. Genuinely preserving A across a stop-loading would need load_model to recheck the cancel before its own teardown, which is a separate design change rather than a race fix.
A stop-loading cancel can land after the pre-spawn marker recheck but while _spawn_subprocess is still creating the queues and process. cancel_load runs off the lifecycle gate, so its _shutdown_subprocess sees _proc not yet alive and no-ops, leaving the freshly spawned worker orphaned; the load then waits for loaded and publishes a model that /unload already reported as unloaded, with a live subprocess nothing later reaps. Recheck the marker once the child exists and tear it down before publishing.
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4f77775058
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| # unload_model's "not in self.models" guard, and the worker's | ||
| # absent-name fallback would then unload its *active* model | ||
| # instead of the already-gone one. | ||
| self.models = {} |
There was a problem hiding this comment.
Recheck cancellation before publishing a loaded model
When /unload cancels an in-flight load off the lifecycle gate, the load thread can already have consumed the worker's loaded response but not yet reached this publish block; cancel_load() can then return success and clear state, after which this block repopulates active_model_name/models and advertises a model the user just cancelled (or whose subprocess was killed). Recheck that model_name is still in loading_models after _wait_response("loaded") and before publishing the successful load.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed genuine and fixed in d20ec54. Traced the interleaving: load_model parks in _wait_response(loaded) holding the lifecycle gate while the worker has already queued its loaded reply. Off-gate cancel_load discards the loading marker (first committed action), clears the mirrors, then _shutdown_subprocess kills the worker and nulls resp_queue. The load thread can still complete its already-blocked queue get on the old queue object (nulling the attribute does not invalidate an in-flight get), return from _wait_response, and be scheduled to run the publish block only after cancel_load has fully returned. cancel_loads post-teardown re-clear only wipes a repopulation that lands during its shutdown window, so a publish that lands after it returns survives it and advertises active_model_name/models for a model /unload already reported cancelled, over a dead subprocess nothing later reaps. The earlier post-spawn recheck sits before _wait_response, so it does not catch a cancel during or after the wait. Fix rechecks model_name in loading_models right before the publish and aborts (clears the local mirrors and returns False; cancel_load owns the subprocess teardown). Added test_load_model_aborts_publish_when_cancelled_after_wait_response, which parks a load past _wait_response, runs cancel_load to full completion, then releases the load: it fails without the recheck (load returns True and active_model_name becomes the cancelled model) and passes with it.
cancel_load runs off the lifecycle gate and discards this model's loading
marker before its subprocess teardown, then re-clears active_model_name/models
after it. A racing load_model can consume its worker's already-queued "loaded"
reply (from the in-flight queue get during cancel_load's shutdown window) and
reach the publish block only after cancel_load has fully returned, so the
post-teardown re-clear cannot undo that publish. The load then advertises a
model /unload already reported cancelled, over a subprocess cancel_load just
killed, with nothing left to reap it.
Recheck that model_name is still in loading_models after _wait_response("loaded")
and before publishing the successful load. cancel_load clears the marker as its
first committed action, so a load that consumed "loaded" during the cancel
observes the removal and aborts the publish instead of surfacing a phantom
loaded model. cancel_load owns and performs the subprocess teardown, so the
aborted load only clears its local mirrors and returns.
Add a regression test that parks a load past _wait_response, lets cancel_load
run to completion (marker discard plus post-teardown re-clear) before the load
consumes "loaded", and asserts the load neither reports success nor publishes
active_model_name/models.
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d20ec54906
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if ( | ||
| loading is not None | ||
| and hasattr(backend, "cancel_load") | ||
| and (request.model_path == loading or request.model_path.lower() == loading.lower()) |
There was a problem hiding this comment.
Normalize loading aliases before waiting on the gate
When /load accepts a shorthand HF id, ModelConfig.from_identifier() stores the loading name in canonical form (for example Qwen3-4B becomes unsloth/Qwen3-4B), but this off-gate cancel path only compares the raw request to get_loading_model() case-insensitively. In that supported shorthand scenario, Stop loading skips this fast path, waits behind the lifecycle gate until the load completes, and then the new stale-name guard in unload_model() treats the raw shorthand as unrelated and no-ops, so /unload reports success while the model remains loaded. Use the same normalization/alias matching here before deciding to wait on the gate.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Verified reachability, and this is not reachable from a supported caller, so leaving as-is.
The off-gate cancel does compare the raw request.model_path against get_loading_model() case-insensitively, and get_loading_model() returns the canonical config.identifier (orchestrator.load_model populates loading_models with config.identifier). The only divergence the case-insensitive comparison misses is the bare-shorthand prefixing that from_identifier applies, turning a slashless non-local id like Qwen3-4B into unsloth/Qwen3-4B.
The studio frontend never sends such a bare shorthand. cancelLoading and the load both send the identical modelId string (cancelLoading uses loadingModelRef.current.id, which is set to the same modelId passed to loadModel), and every id the UI can produce is owner-qualified or an absolute local path. The backend /models catalog builds ids via repo_name.replace('--','/'), the ollama/repo:tag form, or str(model_dir); the hub discover search uses m.name (owner/name); onboarding scopes the hub search to the unsloth owner; and the curated DEFAULT_MODELS_STANDARD and DEFAULT_MODELS_GGUF are all unsloth/... entries. is_local_path returns False for a slashless id and from_identifier then prefixes it, but no supported studio path emits one.
The case-insensitive off-gate match already covers the real owner-qualified divergence, which is the casing that resolve_cached_repo_id_case can change, exactly what test_cancel_load_matches_loading_model_case_insensitively exercises with unsloth/Qwen3-4B vs unsloth/qwen3-4b. So the gated no-op is real in isolation but is not reachable by a real Stop-loading sequence.
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits. |
|
Superseded by #6918, which lands these switch/cancel load-race fixes on a same-repo branch so they can merge. Closing this fork-hosted PR. |
Summary
Switching models while a safetensors or MLX generation was running hung the UI for the whole generation (2-3 min for a long reasoning answer). The inference orchestrator subprocess processes commands sequentially, so a bare
unloadqueued behind the runninggenerateand waited it out. The GGUF backend already avoids this because it cancels and kills itsllama-serverprocess on unload.InferenceOrchestrator.unload_modelnow mirrors that behavior for the shared safetensors/MLX subprocess:mp.Eventthe worker checks each token, so the abort lands within a token (about 0.1s in practice)._gen_lockbefore the unload round-trip so the unload is the soleresp_queuereader, reusing the same serialization the generation path holds. Stale tokens from the cancelled generation are drained so they cannot be read as the unload reply._UNLOAD_GEN_LOCK_TIMEOUT, fall back to tearing the subprocess down so the GPU is freed regardless (the next load spawns a fresh subprocess anyway).MLX shares the same worker and orchestrator, so it is covered too. The GGUF path is unchanged.
Impact
Measured on the running Studio, an unload issued during a live generation dropped from about 2.5 min to 0.53s.
Tests
studio/backend/tests/test_orchestrator_unload_cancel.py:_gen_lock, then unloads;