Repository navigation
fix: harden the OpenXLA continuous-batching engine after #469 - #2848
Merged
Merged
Conversation
The OpenXLA provider hard-coded the queue depth to usize::MAX, its request channel is unbounded, and the engine's admission queue is a plain VecDeque, so nothing refused a request once the batch was full. A client could therefore grow the engine queue and the worker's state map without limit. On the multimodal path each queued entry owns a static-shape embeddings buffer plus its attention bias, so a sustained image stream became unbounded memory instead of the overload error the MLX path returns. Thread the configured bound to the serve worker and check it at every engine-submit site, answering "Server busy: prefill queue full" under the same condition the MLX scheduler's prefill queue uses. Refs #469 Refs #449
A second pass over #469 found two configurations that could not work at all and one unchecked device index: Gemma3n audio was routed by generation budget while its dense PLE is built for one static capacity, so every short audio request on a multi-bucket set failed the PLE shape check; an omitted max_tokens resolves to the checkpoint context window, which is wider than any static graph, so a default client request was always rejected; and token ids reached the embedding gather with no range check, so an out-of-vocabulary id was an out-of-bounds device read. Gemma3n requests now route to the PLE's own capacity, the serve worker clamps the admitted budget to the room the widest shape leaves, and the shim rejects ids outside [0, vocab). The production ragged entries also leaked the runtime call, every buffer view and, in the decode, the previous rank-5 KV pair on any error, and the decode adopted the new pair before reading it back; both now use the cleanup pattern their sibling embeddings entries already used. xla_read_logits requires a dense f32 buffer, the sampler falls back to the finite argmax instead of an arbitrary candidate on non-finite logits, Scheduler drops a Pending.cancelled flag nothing ever set, and bucket cancellation scans instead of trusting stride arithmetic that a dropped bucket invalidates. Refs #469 Refs #449
…h tests The budget clamp read the worker's cached `context_capacity`, which the worker test fixtures set as a literal; asking the engine is the same value in production and keeps a fixture from silently describing a different shape. Record the submitted budget on the fake engine and add the two admission tests the clamp needs: a budget wider than the shape is clamped to the room the prompt leaves, and a prompt that fills the shape is answered with the capacity error instead of a submit. Also add the new worker field to the third test fixture, which the compile gate would otherwise reject. Refs #469 Refs #449
11 of 16 tasks
inureyes
pushed a commit
that referenced
this pull request
Nov 15, 2026
## Summary `cargo clippy --features cuda,xla-iree --all-targets -- -D warnings` stops at one finding, `field_reassign_with_default` in `src/server/batch/xla_worker_tests.rs`. That module is compiled only with `xla-iree`, which the `clippy` job does not enable, so nothing reported it. This writes the two statements as one struct literal. With it clippy passes on the three OpenXLA feature sets. ## Related issues No issue filed; the report is this description. The two lines came in with #2848. ## Type of change - [x] `fix` — bug fix (a lint failure in test code; no behavior changes) ## Before / after `cargo clippy --locked --keep-going <features> --all-targets -- -D warnings` on a DGX Spark (GB10). The three-feature baseline survey ran at local commit `62b6010c7`: `ce6855bc8` plus the unrelated CUDA cache-default test isolation (only `native_env_tests.rs` and its new integration test differ). The affected `xla_worker_tests.rs` blob is identical to clean `ce6855bc8`. The fix is independently based on `ce6855bc8`; the 19-test before/after comparison below starts from clean `ce6855bc8`. | Features | Baseline survey (`62b6010c7`) | This PR | |---|---|---| | `--features cuda,xla-iree` | 1 finding, `mlxcel` (lib test) does not compile | passes | | `--no-default-features --features xla-diagnostics` | the same 1 finding | passes | | `--features cuda,xla-reference-diagnostics` | the same 1 finding | passes | ```text error: field assignment outside of initializer for an instance created with Default::default() --> src/server/batch/xla_worker_tests.rs:1417:5 | 1417 | config.context_size = 8_192; | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ = note: `-D clippy::field-reassign-with-default` implied by `-D warnings` ``` `--keep-going` and `--all-targets` are there so that one failing target cannot hide another: this is the only finding on any of the three. ## Test plan Run on this PR's commit (`89093d179`, one commit on `ce6855bc8`) on a DGX Spark (GB10). - [x] `cargo fmt --all -- --check` - [x] The three clippy invocations of the table: all exit 0 with no finding - [x] `cargo clippy --workspace --all-targets --features cuda -- -D warnings` (the Linux spelling of the template's line), and `cargo clippy -p mlxcel --lib --tests -- -D warnings` with default features, the `clippy` job a fork PR does not get: both pass - [x] `cargo test --profile test-fast --features cuda,xla-iree --lib server::batch::xla_worker -- --test-threads=1`: 19 passed, as on `main`, `a_budget_wider_than_the_shape_is_clamped_instead_of_refused` among them - [x] `cargo check --features cuda,xla-iree --all-targets` and `cargo check --no-default-features --features xla-diagnostics --all-targets`, the two `xla-compile` steps: pass - [x] `scripts/insert_apache_header.py --check`, `scripts/ci/check_cross_repo_refs.py`: OK - [ ] `make verify-test-cuda`: not run. The file is compiled only with `xla-iree`, which that gate does not enable - [ ] Validated with a real checkpoint: not applicable, test code only - [ ] `cargo deny check`: not run and not applicable - [ ] Metal: not built or run here ## Notes for reviewers - **CI does not lint these feature sets.** `clippy` runs `-p mlxcel --lib --tests` with default features, and `xla-compile` runs `cargo check`, which does not run clippy's lints. Swapping `cargo check` for `cargo clippy ... -- -D warnings` in the two `xla-compile` steps would cover it; I have not touched the workflow. ## Checklist - [x] PR title uses a Conventional Commits prefix - [x] One logical change per PR - [ ] Updated `docs/`: no user-facing behavior or supported-model change - [x] Updated `// Used by: ...` comments: no shared function is modified - [x] No secrets, credentials, or `.env` files committed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Post-merge hardening audit of #469 (
feat: productize the continuous-batching engine (#449 M3 Stage 2b)), merged 2026-06-28 asb8bb2170. That PR delivered the OpenXLA continuous-batching engine:XlaBatchEngine, the device-side slot write, the backend-neutralScheduler, the bundled ragged decode graphs, and the reference-equivalence harness. Since merge the feature grew from about 1.5k to 8.2k lines (capacity buckets, host sampling, multimodal admission), so this audit reviews the code as it stands onmainplus the server adapter that consumes it, not only the original diff.Two of the findings break a supported configuration outright, one is a memory-safety hole at the device boundary, and the rest are latent traps or error-path leaks. All are fixed below. The items I could not justify changing without hardware are listed explicitly at the end.
Target PR and issues reviewed
main, merge commitb8bb2170.Findings fixed
1.
--max-queue-depthwas not enforced on the OpenXLA serving path (reliability, unbounded memory)The MLX
BatchSchedulersize-bounds its prefill queue with--max-queue-depthand answers an over-limit request withServer busy: prefill queue full. Nothing did that on the OpenXLA path:new_with_xla_workerhard-codedmax_queue_depth: usize::MAX, the provider-to-worker channel is an unboundedmpsc::channel, the engine's admission queue is a plainVecDeque, andreserve_single_stream_queue_slotis inert there. A client that kept submitting grewScheduler::queueandXlaServeWorker::stateswithout limit, and every queued multimodal entry owns a static-shape payload (capacity x hiddenembeddings plus acapacity x capacitybias, about 38 MB at capacity 2048 and hidden 2560), so a sustained image stream became unbounded memory instead of an overload error.The configured bound now reaches the worker and every engine-submit site checks
engine.pending_len() >= max_queue_depthfirst, answeringServer busy: prefill queue fullunder the same condition shape the MLX queue uses.2. Gemma3n audio could not run on any bucket smaller than the largest (correctness, supported configuration broken)
XlaBucketSet::submit_gemma3n_preparedrouted onsequence_len + max_new_tokens, but the dense PLE is the one prepared payload that is not capacity-agnostic: the audio pipeline builds it once againstXlaBucketSet::largest_capacity()and each bundle validates its first axis against its own capacity. A short audio request (one clip is 188 soft tokens, so about 200 tokens) with a modest generation budget routes to the 256 bucket of a[256, 2048]set, fails that validation, and is answeredGemma3n dense PLE shape [2048, ...] does not match runtime bundle [256, ...]. Every audio request below roughly a 56-token budget was rejected; only budgets wide enough to push it onto the largest bucket worked. A derived multi-bucket set is the default configuration for an image-capable checkpoint, so this was the default path.Gemma3n requests now route to the bucket whose capacity the PLE was built for, and a PLE with no matching bucket is rejected with an explicit message instead of a confusing shape error.
3. The default generation budget exceeded every graph, so a default client request was always rejected (correctness, default configuration broken)
--n-predict -1is the default, andresolve_default_max_tokensturns it into the checkpoint'smax_position_embeddings(131072 for Llama-3.2), which is far wider than any OpenXLA graph. The engine admits oneffective_prompt_len + max_new_tokens <= context_capacity, so a request that omittedmax_tokens(the common OpenAI/Anthropic client behaviour) was deterministically rejected withrequest exceeds the OpenXLA context capacity. The server had nothing between that default and the static shape.The worker now clamps the admitted budget to the room the widest loaded shape leaves after the prefill, and answers a prompt that leaves no room with the capacity error. This mirrors the MLX path, which silently clamps an explicit budget to the effective per-slot window, and it only ever rescues requests the engine would have refused: a budget that fits any bucket is left alone and still routes by its own size.
4. Token ids reached the device gather unchecked (memory safety at the FFI boundary)
Both production ragged entries (
xla_llama_prefill_slot_logits,xla_llama_decode_ragged_impl) validate slot, cache length, positions and the KV pair, but never the token ids, and the emitted graph gathers the embedding table with them and clamps nothing. A token at or above the vocabulary is an out-of-bounds device read oftoken * hidden * 4bytes past the table rather than an error the backend can report. No product path can produce such an id today (sampling draws from the logits row and the tokenizer emits in-range ids), but the contract is enforced nowhere and the padded tail of the token buffer reaches the same gather.Both entries now reject an id outside
[0, vocab), including the padded region, and validate thevocabargument and every pointer before touching IREE.xla_read_logitsadditionally requires a dense f32 buffer, so a mismatched bundle fails instead of reinterpreting f16 rows as f32.5. The production ragged entries leaked everything they had acquired on any error (reliability)
Both functions returned through
XLA_CHECK, which abandons the runtime call, every buffer view and any popped output. The worst site was the decode: it swappedkcache_b/vcache_bto the new pair and then read the logits back, so a readback failure leaked the previous rank-5 KV pair (512 MiB for b4 at capacity 2048), left a pair in place that the caller never saw, and dropped the call's weight references. The serve worker stops on the first error, which bounds the damage there, butXlaBatchEngine::pumpis a public retrying API and the diagnostic engines call these entries directly.Both now use the
XLA_CHECK_GOTO+cleanup:pattern the sibling embeddings entries already used, and the decode reads back before adopting the new cache, so a failed step leaves the resident pair untouched.6. Bucket cancellation trusted index arithmetic a dropped bucket invalidates (latent correctness)
Ids are strided by the requested bucket count, but
XlaBucketSet::cancelderived the owner frombuckets.len(), which shrinks when a bucket fails to compile and is dropped. Cancellation stayed correct only because the function fell back to a full scan, while the documented contract (id % stridenames the owning bucket) was false.cancelnow scans the surviving buckets, and the stride comment says what the stride is actually for: uniqueness.7. Non-finite logits could pick an arbitrary token (robustness)
argmaxcompared with>, which is false against NaN, so a leading NaN pinned the answer to index 0 no matter what the rest of the row held; and when an+inflogit made every softmax exponential NaN, the draw loop could not fire and the sampler returned whichever candidate the sort happened to leave last. Both now fall back to the maximum logit of the finite subset, which is the same answer for every finite row.8.
Pending.cancelleddescribed a mechanism that did not exist (latent trap)Nothing ever set the flag;
Scheduler::cancelremoves the queued entry outright.is_idle,pending_lenandpop_next_pendingall read it anyway, so a future change that started flagging instead of removing would silently make the scheduler report idle with live work queued. The flag and its reads are gone, and the test now asserts the removal.Review findings left as-is
These are recorded rather than changed; each either needs hardware I do not have here or is a policy decision that should not ride in a hardening PR.
xla_ensure_batch_kvzero-fills a full host mirror of the rank-5 KV and uploads it twice on the first admit after a reset (about 512 MiB of H2D at b4/capacity 2048). A device-side fill would avoid it, but that is a device-path change that cannot be run here.xla_llama_ragged_resetaccepts any positivebszwithout tying it to the compiled decode batch; Rust always passes its ownb_max, so only a direct C caller can misuse it.delta = max_position + 1 - sequence_len <= 0), so this would only guard library callers, and a wrong bound here could reject a legitimate path I cannot execute.examples/xla_batch_bench.rsvalidates oneXlaBatchEnginewith greedy decoding only: it never builds aXlaBucketSet, never samples with a seed or penalties, and never cancels. Extending the gate needs an IREE distribution and a GPU run, which this host does not have.Error, the worker stops). That is a deliberate availability policy, not a bug, but it makes the error paths in finding 5 user-visible rather than transient.Validation
cargo fmt --all -- --check: clean.cargo test -p mlxcel-xla --lib: 377 passed, 0 failed, 19 ignored (375 before this PR; the two new sampler tests are the delta).cargo clippy -p mlxcel-xla --all-targets -- -D warnings: clean.text_admission_is_refused_at_the_queue_depth_limit(queue bound refuses without reaching the engine or registering state),a_budget_wider_than_the_shape_is_clamped_instead_of_refusedanda_prompt_that_leaves_no_generation_room_is_refused(finding 3),cancelling_a_queued_request_removes_it_from_the_queue(finding 8),argmax_skips_nan_entriesandnon_finite_logits_fall_back_to_the_greedy_token(finding 7).xla-ireecannot be compiled or run on this host (no IREE distribution). CI'sxla-compilejob (cargo check --features cuda,xla-iree --all-targets, which also compiles the#[cfg(test)]worker tests) is the compile gate, and the runtime behaviour of findings 2 through 5 is covered by reasoning and by that compile rather than by execution here.Refs #469 and #449