Skip to content

fix(studio): recover from a dead Metal GPU queue instead of failing every later request - #11383

Merged
danielhanchen merged 5 commits into
unslothai:mainfrom
Lyxot:fix/studio-mlx-metal-fault
Sep 25, 2026
Merged

danielhanchen merged 5 commits into
unslothai:mainfrom
Lyxot:fix/studio-mlx-metal-fault

Conversation

@Lyxot

@Lyxot Lyxot commented Sep 20, 2026

Copy link
Copy Markdown
Collaborator

What breaks today

Apple's GPU watchdog kills a Metal command buffer that stalls, and every later submission from that process returns SubmissionsIgnored. The process itself stays healthy, so nothing reaps it: a fault raised mid-generation left a live inference worker that failed every subsequent request with "An internal error occurred" and nothing in the log. A failed load was already reaped by load_model, which is why that path recovered on a retry while generation did not.

Three separate places turned an MLX failure into that generic message:

  1. _mlx_optional_fusion guards entry so no optional fusion can fail a load or a request that worked without it. That guard is right for every entry failure but one: once the watchdog has killed a command buffer, the process's GPU refuses every later submission, so there is no unfused path left to fall back to. Logging "continuing with native inference" and carrying on produced a model that answered at 0.097 tok/s and then failed every request.
  2. safe_error_detail recognised none of the Metal wordings. [malloc] Unable to allocate fell through to the generic fallback, and "GPU Timeout Error" matched the connection branch, so a dead GPU was reported to the user as an upstream network problem.
  3. _friendly_gen_stream_error replaced the cause without logging it. All four except GenStreamErrorRaised handlers funnel through it and none logged anything, so a local generation failure left no server-side record at all, unlike its except Exception neighbours.

What changed

A dead queue is re-raised rather than swallowed, which fails the load and lets the worker be reaped -- the only way back to a usable queue. The Metal and allocation wordings are classified ahead of the connection branch, and the cause being replaced is logged.

The orchestrator retires a worker whose queue is dead. Every worker response is inspected where it is read -- _read_resp for direct reads, the new _read_mailbox for dispatcher-routed ones -- rather than where an error is reported. Cancellation consumes a fault and discards it without reporting, and a dead GPU queue makes generation crawl, so pressing Stop is the likeliest way to meet one.

A fault may only retire the worker that produced it. A request's mailbox outlives the process it was opened for, so _WorkerMailbox carries that identity rather than sampling the current one, and _read_resp takes the process handle before the queue, so a reload landing between the two leaves the harmless pairing. Teardown and the model-mirror clear run under _subprocess_shutdown_lock, the lock load_model publishes under, and the mirrors clear only once the process is confirmed dead -- a child that survives SIGKILL keeps its handle and still holds the model.

"Dead queue" is deliberately narrow. mlx/backend/metal/device.cpp formats every MTLCommandBufferStatusError as [METAL] Command buffer execution failed: {description}, so Insufficient Memory shares that wrapper with a watchdog kill, and mlx clears the error when the next commands are encoded. Packing allocates memory native inference never needs, so an allocation failure there is exactly the entry failure the fallback exists for, and matching the wrapper would have refused to load models that run fine unfused. Only the watchdog kill and the refusal after it count.

Validation

python -m pytest tests/test_orchestrator_unload_cancel.py tests/test_audio_tts_cancellation.py \
                 tests/test_inference_dispatcher_resilience.py tests/test_active_generations.py -q
# 1 failed, 236 passed

The single failure, test_active_generations.py::test_a_real_reload_still_refuses_while_chats_stream, fails identically on an unmodified checkout of the target branch. Eighteen mutations of the retirement logic were each confirmed to fail a test.

Risks and tradeoffs

  • The predicate matches Apple's wording (gpu timeout, submissionsignored). If a localizedDescription is ever reworded the retirement stops firing silently, and mlx exposes no typed error to key off instead.
  • Retirement tears the worker down mid-request, so an in-flight request on that worker ends with the error it was already going to get. That is the intent: the queue is already refusing work.
  • A subprocess-level error response carrying no request_id while the dispatcher is running reaches no reader and is dropped. That is pre-existing and unchanged here: MLX generate faults carry an id, and init errors without one are read before a dispatcher exists.

Three ways an MLX failure reached the user as "An internal error occurred" with nothing in the log.

`_mlx_optional_fusion` guards entry so no optional fusion can fail a load or a request that worked without it. That guard is right for every entry failure but one: once Apple's watchdog has killed a command buffer, the process's GPU refuses every later submission, so there is no unfused path left to fall back to. Logging "continuing with native inference" and carrying on produced a model that answered at 0.097 tok/s and then failed every request. A dead queue is now re-raised, which fails the load and lets the worker be reaped -- the only way back to a usable queue.

"Dead queue" is deliberately narrow. `mlx/backend/metal/device.cpp` formats every `MTLCommandBufferStatusError` as `[METAL] Command buffer execution failed: {description}`, so `Insufficient Memory` shares the wrapper with a watchdog kill, and mlx clears the error when the next commands are encoded. Packing allocates memory native inference never needs, so an allocation failure there is exactly the entry failure the fallback exists for; matching the wrapper would have refused to load models that run fine unfused. Only the watchdog kill and the post-kill refusal count.

`safe_error_detail` recognised none of this. `[malloc] Unable to allocate` fell through to the generic fallback, and "GPU Timeout Error" matched the connection branch, so a dead GPU was reported to the user as an upstream network problem. The Metal and allocation wordings are now classified, ahead of that branch.

`_friendly_gen_stream_error` logs the cause it is about to replace. All four `except GenStreamErrorRaised` handlers funnel through it and none logged anything, so a local generation failure left no server-side record at all, unlike its `except Exception` neighbours.
Apple's GPU watchdog kills a command buffer that stalls, and every later submission from that process returns SubmissionsIgnored. The process itself stays healthy, so nothing reaps it: a fault raised mid-generation left a live worker that failed every subsequent request with a generic internal error. A failed load was already reaped by load_model, which is why that path recovered on a retry.

The orchestrator now inspects every worker response where it is read -- `_read_resp` for direct reads, the new `_read_mailbox` for dispatcher-routed ones -- rather than where an error is reported. Cancellation consumes a fault and discards it without reporting, and a dead GPU queue makes generation crawl, so stopping is the likeliest way to meet one.

A fault may only retire the worker that produced it. A request's mailbox outlives the process it was opened for, so `_WorkerMailbox` carries that identity rather than sampling the current one; `_read_resp` takes the handle before the queue, leaving the harmless pairing when a reload lands between the two. The teardown and the model-mirror clear run under `_subprocess_shutdown_lock`, the lock load_model publishes under, and the mirrors clear only once the process is confirmed dead -- a child that survives SIGKILL keeps its handle and still holds the model.
@Lyxot
Lyxot force-pushed the fix/studio-mlx-metal-fault branch from 7f4dabb to 99e6dcf Compare September 20, 2026 19:36
@Lyxot

Lyxot commented Sep 20, 2026

Copy link
Copy Markdown
Collaborator Author

Ran the Codex reviewer and the full CI suite on a staging PR against a pinned base in my fork, because the Codex connector does not respond in this repository and CI here is slower to turn around. Both are green on the exact commit this PR points at, 99e6dcfdc3.

Codex converged with no findings outstanding: Lyxot#64 (comment)

Four findings came out of convergence. Three were real and are fixed in this PR; all three were the same mechanism, so the third fix closes the class rather than adding a third special case.

  • A dead-queue gen_error arriving after a disconnected stream's mailbox had been removed was dropped while routing, so nothing retired the worker and every later request kept failing with SubmissionsIgnored — the failure this PR exists to recover from.
  • The same fault delivered successfully, to a mailbox whose stream then ended before reading it, was equally invisible. The fix is that routing observes every response, delivered or not, so observation never depends on a consumer that may already be gone. Retirement runs off the dispatcher thread, because shutting the worker down joins that thread.
  • A direct reader that takes another request's response could retire the worker before handing the response over, and retiring clears the mailbox registry, so the request the fault belonged to waited out its read timeout for a generic crash message instead of seeing the GPU error. Reads for that path now deliver first and observe afterwards.

One finding was left unfixed, with the reasoning in the thread: after any retirement, sibling streams wait up to one read timeout before _ensure_subprocess_alive ends them with a crash error. That is the shape of every teardown on the base commit — _shutdown_subprocess_locked already cleared mailboxes without a terminal response — so it is not introduced here, and changing it means changing shared teardown rather than dead-queue detection.

CI: all checks green on both PRs — 52 passed and 4 skipped here, 51 passed and 4 skipped on the staging PR.

One CI note worth recording. studiobench UI parity failed twice on the staging PR before passing, on reasoning_toggle at the 100K rung, reported as a 10-character difference in thread scaffolding. It is harness nondeterminism, not a change in behavior: on a later run the null control — which compares the merge base against itself, with no code change at all — produced that same 10-character difference in the opposite direction, and the check has passed since. The change touches backend Python only and no frontend source.

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed this hits the path in studio/backend/utils/utils.py where a Metal watchdog kill still falls through to the connection branch, and that nothing on main retires a worker whose queue is refusing submissions. Will get this reviewed.

@Lyxot

Lyxot commented Sep 22, 2026

Copy link
Copy Markdown
Collaborator Author

@codex review

@danielhanchen danielhanchen self-assigned this Sep 25, 2026
@shimmyshimmer

Copy link
Copy Markdown
Member

Review record for #11383, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#98.

Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found.

Round 1 — reviewed mirror 703bfded1 (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on studio/backend/core/inference/orchestrator.py (on the mirror)

@@ -1152,22 +1199,23 @@ def _direct_reader(self, request_id: str):
 
         Returns (read_one, drain, release).
         """
-        mailbox: queue.Queue = queue.Queue()
+        mailbox = _WorkerMailbox(self._proc)
         with self._mailbox_lock:
             self._direct_mailboxes[request_id] = mailbox
 
         def read_one(timeout: float = 1.0):
             try:
-                return mailbox.get_nowait()
+                return self._read_mailbox(mailbox)
             except queue.Empty:
                 pass
             thread = self._dispatcher_thread
             if thread is not None and thread.is_alive():
                 try:
-                    return mailbox.get(timeout = timeout)
+                    return self._read_mailbox(mailbox, timeout)
                 except queue.Empty:
                     return None
-            resp = self._read_resp(timeout = timeout)
+            worker = self._proc  # handle before queue, as in _read_resp
+            resp = self._read_resp(timeout = timeout, observe = False)

P2 Badge Keep the worker snapshot paired with the response

When a worker replacement occurs after this snapshot but before _read_resp() takes its own worker/queue snapshots, the response can come from the replacement while _observe_response() is given the predecessor. The identity check then suppresses retirement; for an unaddressed response or one handed to an abandoned mailbox, no later reader corrects it, leaving the replacement's dead Metal queue resident. Return the worker captured alongside the response from _read_resp() (or otherwise snapshot the pair atomically) rather than independently sampling _proc here.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from danielhanchen:

Not changing this. The two snapshots are adjacent with nothing blocking between them, the same window as the handle-before-queue pairing inside _read_resp that the suggested fix keeps, so a reload landing there is missed either way. The miss is also not permanent: a dead Metal queue refuses every later submission, so the replacement's next request returns SubmissionsIgnored, is observed against the right worker, and retires it.

Round 2 — reviewed mirror 703bfded1 (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] (on the mirror)

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: 703bfded1a

View security finding report

Only the user who started this review can view the report in Codex.

No triage reaction was recorded on the mirror

Round 3 — reviewed mirror a1b1c92a6f (this PR's de092db96)

chatgpt-codex-connector[bot] (on the mirror)

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: a1b1c92a6f

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror a1b1c92a6f (this PR's de092db96).

This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 25, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 25, 2026
@danielhanchen
danielhanchen merged commit 8d15d04 into unslothai:main Sep 25, 2026
50 of 52 checks passed
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…very later request (unslothai#11383)

* fix(studio): report a dead Metal queue instead of hiding it

Three ways an MLX failure reached the user as "An internal error occurred" with nothing in the log.

`_mlx_optional_fusion` guards entry so no optional fusion can fail a load or a request that worked without it. That guard is right for every entry failure but one: once Apple's watchdog has killed a command buffer, the process's GPU refuses every later submission, so there is no unfused path left to fall back to. Logging "continuing with native inference" and carrying on produced a model that answered at 0.097 tok/s and then failed every request. A dead queue is now re-raised, which fails the load and lets the worker be reaped -- the only way back to a usable queue.

"Dead queue" is deliberately narrow. `mlx/backend/metal/device.cpp` formats every `MTLCommandBufferStatusError` as `[METAL] Command buffer execution failed: {description}`, so `Insufficient Memory` shares the wrapper with a watchdog kill, and mlx clears the error when the next commands are encoded. Packing allocates memory native inference never needs, so an allocation failure there is exactly the entry failure the fallback exists for; matching the wrapper would have refused to load models that run fine unfused. Only the watchdog kill and the post-kill refusal count.

`safe_error_detail` recognised none of this. `[malloc] Unable to allocate` fell through to the generic fallback, and "GPU Timeout Error" matched the connection branch, so a dead GPU was reported to the user as an upstream network problem. The Metal and allocation wordings are now classified, ahead of that branch.

`_friendly_gen_stream_error` logs the cause it is about to replace. All four `except GenStreamErrorRaised` handlers funnel through it and none logged anything, so a local generation failure left no server-side record at all, unlike its `except Exception` neighbours.

* fix(studio): retire an inference worker whose Metal queue has died

Apple's GPU watchdog kills a command buffer that stalls, and every later submission from that process returns SubmissionsIgnored. The process itself stays healthy, so nothing reaps it: a fault raised mid-generation left a live worker that failed every subsequent request with a generic internal error. A failed load was already reaped by load_model, which is why that path recovered on a retry.

The orchestrator now inspects every worker response where it is read -- `_read_resp` for direct reads, the new `_read_mailbox` for dispatcher-routed ones -- rather than where an error is reported. Cancellation consumes a fault and discards it without reporting, and a dead GPU queue makes generation crawl, so stopping is the likeliest way to meet one.

A fault may only retire the worker that produced it. A request's mailbox outlives the process it was opened for, so `_WorkerMailbox` carries that identity rather than sampling the current one; `_read_resp` takes the handle before the queue, leaving the harmless pairing when a reload lands between the two. The teardown and the model-mirror clear run under `_subprocess_shutdown_lock`, the lock load_model publishes under, and the mirrors clear only once the process is confirmed dead -- a child that survives SIGKILL keeps its handle and still holds the model.

* Trim comments in the Metal queue recovery change

* Drop blank lines left by removed class docstrings

* Drop four restating docstrings

---------

Co-authored-by: Daniel Han <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants