Skip to content

fix(mlx-sys): native errors reach the Rust turn error; GPU OOM is classified - #379

Merged
Brooooooklyn merged 1 commit into
mainfrom
feat/perf-f1-native-error-text
Nov 13, 2026
Merged

Brooooooklyn merged 1 commit into
mainfrom
feat/perf-f1-native-error-text

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Base: fix/main-ci-after-344 (#377, the main CI fix). Merge #377 first; this PR then holds one commit.

What

A native MLX/Metal error raised inside a lazy eval (kernel or pipeline failure, GPU OOM, command-buffer error) now reaches the Rust error that the turn returns, with MLX's own text. The scheduler's GPU-OOM check (is_gpu_out_of_memory → note_gpu_oom, Splash NativeRuntime::executionFailed) can then match it, fail the row metal_out_of_memory: and reset the ledger. This covers prefill, the first sample and every scheduler decode step.

Why

P0 (code-only probe, a throw inside PagedPrefillAttention::eval_gpu) showed the text survived only when the paged prefill layer barrier caught it. On the sample path and on every decode token read it was lost:

  • ensure_readable caught the throw and returned false. item_at_int32 then reported Failed to extract int32 scalar (array must have size=1), so the OOM check missed it and the ledger count stayed 0.
  • mlx_synchronize only printed to stderr. MLX throws a failed GPU command's error once (at the next encode, synchronize or event wait, mlx/error.h) and then clears it, so a dropped error is gone and the turn keeps running on what the failed command wrote.
  • MxArray::eval (mlx_array_eval) at the first sample, at the paged prefill chunk boundary and at the scheduler's decode sample (batch_greedy_tokens, the greedy MTP verify) swallows a wait-time error the same way. The decode epilogues then also fell back to per-row sampling on any error, which reads what the failed command wrote.

Change

ensure_readable / mlx_synchronize ──catch──► per-thread native error slot
        ▲ (each item_at_* / synchronize entry clears it first)
        │
item_at_* ──false──► mlx_take_native_error (copy + clear) ──► "MLX eval failed in array_item_at_int32: <MLX text>"
mlx_synchronize ──false──► synchronize_and_clear_cache_checked ──► "MLX synchronize failed in <context>: <MLX text>"
eval_arrays_with_context ──Err──► "MLX eval failed in <context> while materializing N arrays: <MLX text>"
                                                    │
hybrid scheduler: fail the row ──► settle_step ──► note_gpu_oom ──► metal_out_of_memory: … ; ledger count +1

Scheduler decode step after this PR:

forward ──► greedy wave? ──yes──► argmax ──► eval "scheduled_greedy_sampling"
               │                    │ shape/graph miss        │ Err: every batched row fails (no fallback)
               │                    └──► per-row sampling ◄───┘ Ok: tokens
               no
               └──► per-row samplers ──► eval "scheduled_sampling"
                                            │ GPU OOM: every row fails (no per-row retry)
                                            │ other Err: per-row retry (unchanged)
speculative (MTP / DSpark / DFlash) verify ──► greedy: eval "scheduled_verify_greedy", Err fails every row
                                           ──► forced row: eval "scheduled_verify_forced"
                                           ──► per-row greedy accept: eval "speculative_greedy_accept"
  • crates/mlx-sys: the slot in mlx_common.h; mlx_synchronize returns a status; mlx_take_native_error; the test hook mlx_test_fail_next_native_call (no production caller; the next eval, read or synchronize on this thread throws once).
  • array/data.rs: item_at_{int32,uint32,float32} attach the slot's text. array/memory.rs: synchronize_and_clear_cache_checked(context). The public MxArray::eval signature is unchanged; the unchecked synchronize* helpers keep their old behaviour for every other caller.
  • engine/hybrid_scheduler.rs: the synchronize after a non-final prefill slice, after a replay slice and after the first sample is checked. The first sample is evaluated with eval_arrays_with_context. A failed batched greedy eval fails each batched row with the native text.
  • engine/batch_sampling.rs: batch_greedy_tokens_or_fallback returns Result<Option<_>>. A shape or graph miss still falls back to per-row sampling (Ok(None)); a failed eval or read is an error. In evaluate_pending_samples, a GPU OOM at the wave eval fails every row instead of the per-row retry; other errors keep the retry.
  • engine/hybrid_scheduler/speculative.rs: the greedy verify eval and the forced-row eval are checked; a failed greedy verify fails every row of the wave (tickets still commit with keep=0) instead of the per-row fallback.
  • engine/dspark_turn.rs: accept_dspark_proposal's greedy argmax eval is checked (one line). It is reached on the scheduler decode path when the wave is mixed; the whole-turn DSpark caller shares it and already handles its Err.
  • models/qwen3_5{,_moe}/paged_forward.rs: the non-final chunk residual eval (text and VLM prefill) uses eval_arrays_with_context. This closes the #344 gap where the error was only logged.

Per-step cost: the decode evals were already one sync eval each; the checked call adds the error test and a one-element handle Vec.

Error text, before → after

failure before (reaches the turn) after OOM matched / ledger
throw while encoding, first eval at the sample (P0 run B) Failed to extract int32 scalar (array must have size=1) metal_out_of_memory: a GPU command exhausted Metal memory (MLX eval failed in scheduled_prefill_sample while materializing 1 arrays: [malloc] Unable to allocate 1073741824 bytes.); … no / 0 → yes / 1
error thrown at the batched greedy decode sample swallowed; decode went on (or fell back to per-row sampling) metal_out_of_memory: … (MLX eval failed in scheduled_greedy_sampling while materializing 1 arrays: [malloc] …); … no / 0 → yes / 1
GPU OOM at the non-greedy sampling wave per-row retry sampled what the failed command wrote every row: MLX eval failed in scheduled_sampling while materializing N arrays: [malloc] … no → yes
error at the greedy MTP verify eval swallowed; per-row acceptance went on every row: MLX eval failed in scheduled_verify_greedy while materializing 1 arrays: <MLX text> no → yes
decode token read (item_at_int32) Failed to extract int32 scalar (array must have size=1) MLX eval failed in array_item_at_int32: [malloc] Unable to allocate … no → yes
error thrown at the synchronize after the sample stderr only; the turn went on metal_out_of_memory: … (MLX synchronize failed in scheduled_prefill_sample_sync: [malloc] …); … no / 0 → yes / 1
error at a dense or MoE prefill chunk eval trace file only; the next chunk ran MLX eval failed in paged_prefill_chunk while materializing 1 arrays: <MLX text> no → yes
throw at the layer barrier (P0 run A) already carried the text unchanged yes / 1

Tests and mutations

Each mutation was a runtime switch in one test build, checked red with the switch on and green with it off, then removed (git grep MLX_MUT = 0). A mutation at a checked eval or synchronize still calls the checked function and only drops its result, so the injected throw is consumed exactly as a swallowing caller would.

test mutation (→ red)
array::data::native_error_tests::a_failed_read_carries_the_native_error F1_ITEM: a failed read drops the native text
array::data::native_error_tests::a_stale_native_error_never_attaches F1_STALE: item_at_* does not clear the slot first
array::data::native_error_tests::a_failed_synchronize_returns_the_native_error F1_SYNC: the checked synchronize ignores the status
engine::hybrid_scheduler::tests::a_native_gpu_oom_at_the_first_sample_fails_the_turn (sample eval + synchronize; checks the metal_out_of_memory: reply and ledger count 1) F1_SAMPLE_EVAL, F1_SCHED_SYNC: the checked call's result is dropped
engine::hybrid_scheduler::tests::a_native_gpu_oom_at_the_decode_sample_fails_the_turn (batched greedy decode; metal_out_of_memory: reply, ledger count 1) F1_GREEDY_EVAL: the greedy eval's result is dropped; F1_GREEDY_FALLBACK: a failed greedy eval falls back to per-row sampling
engine::batch_sampling::tests::a_native_error_at_the_greedy_eval_fails_the_wave F1_GREEDY_EVAL, F1_GREEDY_FALLBACK
engine::batch_sampling::tests::a_gpu_oom_at_the_sampling_wave_fails_every_row F1_SAMPLING_RETRY: a GPU OOM at the wave is retried per row
engine::hybrid_scheduler::speculative::tests::a_native_error_at_the_greedy_verify_fails_the_row (Qwen3.5 native MTP) F1_VERIFY_GREEDY: the verify eval's result is dropped
models::qwen3_5::model::paged_construction_tests::a_failed_dense_prefill_chunk_eval_fails_the_prefill F1_CHUNK: the chunk eval's result is dropped
models::qwen3_5_moe::paged_forward::tests::a_failed_moe_prefill_chunk_eval_fails_the_prefill F1_MOE_CHUNK: the chunk eval's result is dropped

Fault injection uses mlx_test_fail_next_native_call. It follows the repo's existing bridge_testing per-thread test-flag pattern, so it is a permanent hook, not an MLX_MUT switch. In Rust, fail_native_call_at(context, text) arms it only for the checked eval or synchronize with that context. That Rust code is #[cfg(test)] only. The C++ check on the hot path is a single empty-string test of a thread-local.

Gates

gate result
cargo fmt --all --check pass
cargo clippy --workspace --all-targets -- -D warnings pass
mlx-core --lib (full, one build, --test-threads=1) 4833 passed, 0 failed, 221 ignored
cargo test -p mlx-paged-attn --lib --tests 16 binaries (211 lib), 334 passed, 0 failed
cargo test --workspace --test '*' --no-fail-fast 112 binaries, 323 passed, 0 failed, 193 ignored
#[napi] surface unchanged (no index.d.cts change)
Live T=0 smoke, qwen3.5-0.8b bf16, 48 tokens, MLX_PAGED_PREFILL_CHUNK_SIZE=64, whole-turn and MLX_CONTINUOUS_BATCHING=1 byte-equal before (#377 base) / after in both modes (gate build profile, no fat LTO)

Not covered

  • A real command-buffer failure ([METAL] Command buffer execution failed: Insufficient Memory) is not reproduced. The tests inject the throw at the native entry point, which is where MLX raises such an error. MLX's ordering (stored on the encoder, thrown once at the next encode, synchronize or event wait) is from reading device.cpp and error.h.
  • The synchronize after a non-final prefill slice and after a replay slice, the VLM chunk evals (dense and MoE), the forced verify row eval and the per-row greedy DSpark accept get the same one-line change but have no dedicated mutation test.
  • A non-OOM failure at the non-greedy sampling wave still retries per row (the existing row-isolation contract). Only a GPU OOM skips the retry.
  • Other swallowing MxArray::eval sites (MTP prompt-hidden evals, whole-turn paged_turn/mtp_turn/dspark_turn synchronizes, other families' whole-turn decode) are unchanged. Only the scheduler acts on a synchronize status.
  • to_float32/int32/uint32 and the probability_* readers do not attach the text, since they are not on the token path. The slot never leaks into a later item_at_* or synchronize because both clear it on entry.

Review notes

  • Rejected (local Codex): "an already-signaled failed event is detached without its error". On the pinned MLX, array::is_available() → detach_event() → event.check_error() (mlx/array.h:417, upstream #3742) throws the stored error; the completion handler stores it (device.cpp:766) before signaling (:773). So the checked eval returns Err.
  • Known gap, not measured: an eval that spans several command buffers, where an earlier buffer fails and the last succeeds, can pass its wait before the handler marks the event; the error then surfaces at the next encode on that stream (one step late through a checked eval, lost through an unchecked MxArray::eval). Upstream's blocking Event::wait has the same window.

🤖 Generated with Claude Code

@Brooooooklyn Brooooooklyn added the model-e2e Run the heavy Model E2E workflow (per-family real-checkpoint tests) on this PR label Nov 13, 2026
@coderabbitai

coderabbitai Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 556b9029-5280-4cbd-9726-1520dea0a680

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-13T06:07:10.430460Z fbb38ec New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

…ssified

A native MLX/Metal failure inside a lazy eval lost its text: host reads
(`item_at_*`) reported "Failed to extract int32 scalar", `mlx_synchronize`
only printed to stderr, and the swallowing `MxArray::eval` at the first
sample, at paged prefill chunk boundaries and at the scheduler's decode
sample dropped it. MLX throws a failed GPU command's error once, so decode
went on with what the command wrote. The scheduler's GPU OOM check (Splash
`NativeRuntime::executionFailed`) never matched.

- A per-thread native error slot: `ensure_readable` and `mlx_synchronize`
  fill it, each `item_at_*`/synchronize entry clears it first, and
  `mlx_take_native_error` hands it to Rust and clears it.
- `item_at_{int32,uint32,float32}` carry it: "MLX eval failed in
  array_item_at_int32: <MLX text>".
- `mlx_synchronize` returns a status; `synchronize_and_clear_cache_checked`
  fails with the text. The hybrid scheduler uses it after a non-final
  prefill slice, a replay slice and the first sample, and evaluates the
  first sample with `eval_arrays_with_context`, so the row fails and
  `note_gpu_oom` counts it.
- Scheduler decode: the batched greedy sample, the greedy verify, the
  forced verify row and the DSpark greedy accept use
  `eval_arrays_with_context`. A failed greedy eval fails the wave's rows
  instead of falling back to per-row sampling (a shape miss still falls
  back), and a GPU OOM at the sampling wave fails every row instead of a
  per-row retry.
- Qwen3.5 dense and MoE paged prefill (text and VLM) evaluate the chunk
  residual with `eval_arrays_with_context`, so a failure there ends the
  prefill instead of the next chunk running on what it wrote.
- Test hook `mlx_test_fail_next_native_call` (no production caller) makes
  the next native eval, read or synchronize throw once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Brooooooklyn
Brooooooklyn force-pushed the feat/perf-f1-native-error-text branch from 4ab1d29 to fbb38ec Compare November 13, 2026 06:05
@Brooooooklyn
Brooooooklyn merged commit 5ed8b5d into main Nov 13, 2026
15 checks passed
@Brooooooklyn
Brooooooklyn deleted the feat/perf-f1-native-error-text branch November 13, 2026 06:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

model-e2e Run the heavy Model E2E workflow (per-family real-checkpoint tests) on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant