Repository navigation
feat(server): a stop match ends decode and commits up to the match - #371
Conversation
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the
|
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8106c2d30c
ℹ️ 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".
c0ce73b to
f37b08a
Compare
3a56a8e to
1c1ef3e
Compare
f37b08a to
c2b7a02
Compare
A /v1/messages stop_sequences match (streaming or not) calls ChatStreamHandle.stop (Splash RuntimeCall.stop): a stop bit plus the cancel flag, so decode ends within one step through the commit epilogue and the turn finishes "stop". ChatSession commits the text up to the match with no tool calls and replays the full history next send. A stop on a preempted, waiting or replaying turn with tokens ends as a completion. qwen4_exp decode passes end at the pass boundary on a cancel instead of failing mid-forward. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A stop that lands inside a preempted turn's replay prefill slice fails the slice on the live cancel flag; execute_prefill now ends the turn through stop_vacates as a completion (Splash Engine::stop -> settle). ChatSession.stop latches its cut only once the native stop is accepted, so an early stop returns false and changes nothing (Splash RuntimeCall._request_end). A raw-replay family (LFM2) commits its raw reasoning block followed by the cut. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A stop on a preempted or waiting turn ended through finish_completed, which installed owner state and ran activate_paged_seq before it read vacated_stop. With peers holding both Qwen3.5 recurrent units the activation failed and the stop became an error. The vacated arm now releases the turn's pages by sequence id and emits the result without reacquiring a slot (Splash vacateLane -> finish(Stop)). Co-Authored-By: Claude Opus 5.5 <[email protected]>
1c1ef3e to
7ba810f
Compare
…372) Stage S36b of the Splash int8 KV alignment (stack #344). Base: S30 (#371). This PR makes split qwen35 / qwen35moe GGUFs load, and refuses any header tensor the loader does not read. It also adds a header-only check that `mlx download` runs before it fetches any weight byte. Splash: `GgufFile` over every part, `GgufImage` `Problems::addUnread`, `install/upstream.py` `gguf_target` + `model-check`, `install/gguf.py` `flint_stop_tokens`. ``` before: NAME-00001-of-00003.gguf ──► reject_split ──► "merge with llama-gguf-split" header ──► plan (an extra tensor such as attn_q.bias is silently ignored) mlx download ──► fetch every byte ──► the load finds the problem after: part 1 ──► resolve_main_parts (siblings by name) ──► check_split_parts ──► merge_split_headers ──► plan ──► refuse_unread_qwen35_tensors ──► read each part (one page-cache decision for the whole set) mlx download ──► range-read each target's header (8 MiB reads) ──► checkGgufHeaders ──► download, or refuse with nothing fetched ``` ## Changes - **Split loads (qwen35 / qwen35moe).** `resolve_main_parts` finds the parts by name beside part 1, before it resolves any link (Hugging Face snapshot links point to blobs that have other names). `check_split_parts` applies the Splash `GgufFile` rules: `split.count` must equal the number of files, a later part's `split.no` (U16 / U32) must equal its place, `split.tensors.count` must equal the total, and no tensor name may repeat. `merge_split_headers` builds the one header the plan reads. `GgufCheckpoint.main` / `PreloadInput.main` now hold a list of parts (`GgufMain`, `PreloadMain`). Each part is read with its own header, and the page-cache decision is taken once from the bytes of all parts. - **Records.** `gguf-source.json` now lists every part (`main` and `main_identity` are arrays). The cache marker adds one `part_hex=` line per extra part, and the sweep checks each of them. The cache key and `source_identity_sha256` cover every part. The format goes from 8 to 9, so older entries age out. - **Unread tensors.** `refuse_unread_qwen35_tensors` runs last in `plan_gguf_import`. A tensor is accepted only if the loader reads it: the per-layer norms, the GDN or full-attention mixer chosen by `full_attention_interval`, the dense or MoE FFN, and the three global tensors. The `nextn_predict_layers` blocks after the decoder are exempt. Faults are reported in Splash `Problems` form, for example `attn_q.bias (unused) in 1 layer`. `nextn_predict_layers` must agree with the inline MTP block. - **Header stop ids.** `tokenizer.ggml.eog_token_ids` (a non-empty integer list, otherwise refused) and the vocabulary id of `<|endoftext|>` (Splash Qwen `.stopTokens`) are merged into the asset `generation_config.json` `eos_token_id`, and its other keys are kept. The merge is skipped when the conversion writes into the GGUF's own folder. - **Header rules in `parse_gguf_reader`** (Splash `GgufFile::parse`): - at most 16384 tensors and 16384 metadata keys; - no metadata key twice and no tensor name twice; - rank 1..4 and no zero dimension; - alignment a power of two of at most 64 KiB; - each tensor offset aligned, and each row a whole number of blocks; - a part with no tensors may end at its header. - **`#[napi] checkGgufHeaders(dir)`.** It applies Splash `findTargetGgufs` (one file, or the parts of one name), the file and split rules, and then, for qwen35 / qwen35moe, the import plan every load runs. gemma4, clef and muse-glimmer refuse a split. Other architectures pass. - **`mlx download`.** `checkGgufTargets` groups the selected GGUFs into targets, and a split target must hold every part. For each part it range-reads `[0, end of the tensor table)` with `readGgufHeader` (new `@mlx-node/lm/gguf-metadata` subpath). It also fetches the target folder's `config.json` when that file is selected, then runs `checkGgufHeaders`. The native addon is imported only when a GGUF target is selected. On a refusal, the completion marker is restored and nothing is fetched. - **Header readers.** `readGgufHeader` keeps every byte it reads, up to 128 MiB (Splash `Metadata.MAX_BYTES`). Discovery (`readGgufArchitecture`, now over `readGgufSourceArchitecture`) keeps the old 64 KiB seeking window, so a skipped metadata array is never read or held. - **Discovery.** A hand-written `ggufSplitPart` replaces the split regex, and the qwen3_5 / qwen3_5_moe rows have `split: true`. The XL and Bonsai name tests run on the stem, so part 1 of a split XL GGUF is found and later parts are never listed. - **Docs.** `docs/cli.md`, `docs/models.md` and `docs/convert-quantize.md` cover split loads, the unread-tensor rule, the parts listed in `gguf-source.json`, and the header check before download. ## Deleted - `reject_split` inside `GgufFileHandle::open`. It now runs in `GgufSourceSet::open` for one-file mains and for the companion. - The scalar `main` / `main_identity` shape of `gguf-source.json` (reader and writer). - The `PreloadFile` tuple for the main GGUF. The companion keeps it. - The split regex in `supportedGgufName`. - `general.alignment ... .max(1)`, replaced by the Splash rule. ## Tests - Rust: `split_gguf_loads_like_one_file` (dense and MoE: the 3-part load is bit-equal to the one-file load, including the reload from the asset dir; checkpoint bytes are the sum of the parts), `split_parts_follow_the_gguf_file_rules`, `split_reads_share_one_page_cache_decision`, `sweep_reads_every_part_of_a_split_entry`, `plan_refuses_unread_qwen35_tensors`, `header_eog_ids_join_generation_config`, `check_gguf_headers_reads_header_only_copies`, `parse_gguf_refuses_what_splash_refuses`, `ple_table_rows_bf16_and_f16_at_width_160`. - TS: `__test__/cli/download-model-gguf-check.test.ts` (with `tiny-gguf.ts`), plus new cases in `model-discovery.test.ts` and `gguf-metadata.test.ts` (chunk edges, the 16385-tensor refusal, a 248k-entry token array, discovery past a 32 MiB skipped array reads < 1 MiB). - Named mutations (`MUTATIONS.md`). Each one is red with its switch on and green with it off: | id | mutation | |---|---| | G5 | BF16/F16 row rounded up to 256 values | | G6 | header stop ids not merged | | G6b | `<\|endoftext\|>` not looked up | | G2 | unread-tensor rule returns Ok | | G1b | only part 1 read | | G1b2 | `split.no` place check skipped | | G1d | per-part page-cache decision | | G1e | sweep ignores `part_hex=` | | G1c | XL test on the full split name | | G3b | offset alignment check skipped | | G3c | header returned one byte short | | G3 | `checkGgufHeaders` not called | | G3a | addon imported before the no-GGUF return | | B1 | discovery uses the byte-keeping header reader | - Gates: see the table below. | gate | result | |---|---| | `cargo fmt --all -- --check` | clean | | `cargo clippy --workspace --all-targets -- -D warnings` | clean | | mlx-core `--lib`, one binary, `RUST_TEST_THREADS=1` | 4,750 passed, 0 failed, 220 ignored | | `yarn build:native` | ok; `index.d.cts` copies in sync | | `yarn typecheck`, `yarn tsc -b --force` (23 projects) | clean | | `vp test` on `packages/lm/__test__`, `__test__/cli`, `packages/cli/__test__`, `packages/dashboard/__test__`, plus the agent `models` / `family-completeness` / `catalog-native-free` and desktop `child-entries` tests | 70 files passed, 1 skipped; 1,426 tests passed, 1 skipped | | `vp fmt --check` and `vp lint --type-aware --type-check` on the touched files | clean; for the `packages/lm/__test__` files, a per-file lint reports TS2591 (no node types) on imports this PR does not change, because no tsconfig covers that folder | ## Gaps - qwen4exp (Flash Next) gets no unread-tensor rule, and its `index_gguf` keeps its own split checks. Gating a change there would mean loading Flash Next. - gemma4 / clef / muse-glimmer still refuse split GGUFs, and `mlx convert` still reads one file. - A fused `ffn_gate_up_exps` is refused, not loaded. The name map, quant entries, t64 plan and packed-row split are not verified on the native k-quant route, and no known qwen35moe GGUF carries this tensor. - The native load takes a file path, not a folder, so several unrelated names beside part 1 are not refused at load. `checkGgufHeaders` does refuse them. - The header check runs only in the CLI. Dashboard downloads are not checked, and the projector header and the BF16 refusal (`require_quantized`) are not ported. - An F16 PLE table is not rounded to bf16 at the gather (Splash `storedTable`). - Narrow integer metadata arrays (u8 / u16 / i8 / i16) parse as empty, so such an `eog_token_ids` is refused. Ids outside u32 are refused too, where Splash accepts negative ids. - There is no compiled-vs-eager bias gate, because this base has no compiled target attention. Refusing the bias is Splash's own answer. - Each part uses its own `general.alignment`, while Splash applies part 1's to every part. - `checkGgufHeaders` plans only qwen35 / qwen35moe, and unknown architectures pass (Splash `withFamily` refuses them). - The eog key rule is applied to Qwen GGUFs (Splash reads it for Flint only). - The stop-id merge is skipped when converting into the GGUF's own folder. - Discovery checks only part 1's name, so an interrupted split download is listed and then fails at load, naming the missing part. ## Not in this PR (live, not run) - L1: `checkGgufHeaders` on every local qwen35 / qwen35moe GGUF (header bytes only). - L2: a 3-part split of AgentWorld 35B-A3B Q4_K_XL loads and decodes the same text as the one file (AR, T=0). - L3: Hub header check on DeepSeek V4.1 Flash and Qwen3.5-122B splits (range reads only, < 64 MiB of headers). - L4: the CLI refuses an incomplete split selection before any download. - Scripts: `LIVE.md`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
Stage S30 of the Splash int8 KV alignment (stack #344). Base: S14 (#370).
A
/v1/messagesstop_sequencesmatch now ends decode at the step the model is running, streaming or not, and the turn finishes as a completion. Splash:stop_matched→RuntimeCall.stop→Engine::stop→settle→finish(Stop);release→vacateLanekeeps the generated KV in the cache.Changes
ChatStreamHandle.stop()stores a stop bit, then the cancel flag (Release / Acquire).StreamTxwatches both. Its sink renames a done"cancelled"to"stop"when the stop bit is set and the turn generated tokens. With 0 tokens the turn stays cancelled.handle_preempted), a waiting turn (reap_cancelled_waiters) or a turn replaying its prefill (HybridStepExecutorand qwen3 raggedQwenStepExecutorprefill rows) that holds tokens now ends as a completion, not as the cancelled error. This includes a stop that lands inside a replay slice the backend is running: the slice fails on the live cancel flag ("prefill cancelled"), andexecute_prefillends the turn throughstop_vacates. The qwen3 ragged forward never reads the cancel flag, so its replay slices cannot fail this way. Its leftover pages are released by sequence id (its full blocks were registered at preemption) and its owner state is dropped. It takes no recurrent slot back and installs no owner state (SplashvacateLane→finish(Stop)), so it completes even when peers hold both recurrent units. The done chunk goes throughemit_paged_turn_result, the result half offinish_paged_turn, split out for this.Decoder::step,verify_chunkand the scheduled decode / propose / verify / commit entries finish their pass, and the step-boundary snapshot ends the turn. A batched pass no longer fails its peer rows on one row's stop. Prefill and media still stop on the flag._runChatStream: one end latch for cancel and stop (SplashRuntimeCall._request_end). A stop keeps reading to the done chunk.ChatStreamProgressRefbecomesChatStreamControl { read, stop }.ChatSession.stop(committedText): records the cut only when the native stop is accepted (SplashRuntimeCall._request_end). Before the native stream starts it returnsfalseand changes nothing, so the caller can retry. The done event carries the cut,toolCalls: []andfinishReason: 'stop'. History commits the cut, andneedsFullReplayis set. For a raw-replay family (LFM2 / lfm2_moe) the committed content is the raw text before the visible stream (the reasoning block) followed by the cut. If the raw text does not end with the visible stream, it falls back to the structured message.stoponce, on the first match. The committed text is the text the response holds.stop_sequencesruns the stream internally. The collector feeds visible deltas through the sameToolCallTagBuffer→StopSequenceBufferorder, builds the text with theselectCommittedStreamTextrule (Gemma4 / Muse-Glimmer delta-only text), and returns the match and cut thathandleNonStreaminguses.selectCommittedStreamTextis exported from@mlx-node/lm.docs/cli.md(stop behaviour,output_tokensovershoot) anddocs/models.md(ChatSession.stop).Deleted
ChatStreamProgressRefandprogressRef. Replaced byChatStreamControl/control.cancelRequestedandcancelledin_runChatStream. Replaced by the one end latch.Tests
Each named mutation was red with the mutation on and green with it off (
MUTATIONS.md):engine::napi_glue::tests::a_stopped_stream_finishes_stop. Mutation: the sink skips the rename to "stop".engine::decode::run_decode_loop_tests::stop_at_token_20_ends_decode_within_one_step. Mutation:stop()sets only the stop bit, and the loop runs to the 32,000 cap.qwen3_5::model::dflash2_park_tests::a_stopped_turn_commits_through_the_match. Mutation:finish_paged_turnaborts the cancelled turn's pages, and the prefix hit stops inside the prompt.qwen4_exp::tests::a_stop_on_a_preempted_turn_finishes_stop. Mutation:stop_vacatesreturns false.qwen3::model::tests::a_stop_on_a_ragged_prefill_row_ends_as_a_completion. Mutation: the ragged prefill row ignores the stop.qwen4_exp::tests::a_cancel_during_decode_ends_at_the_pass_boundary. Mutation:check_cancelledignoresdecode_pass.qwen35-stream.test.ts, "stop shares the cancel latch…". Mutation: a stop pushes the abort marker.chat-session.test.ts, "commits the text up to the match" and "replays the full history". Mutations: commit the full text; skip the full replay.messages-handler.test.ts, streaming and non-streaming "a stop match ends decode within one step". Mutation: the handler or the collector never calls stop.messages-handler.test.ts, "non-streaming with stops keeps delta-only text". Mutation: the collector usesdone.text.messages-handler.test.ts, "non-streaming takes the stop from the decode deltas". Mutation: the response rescans the final text.qwen4_exp::tests::a_stop_inside_a_replay_prefill_slice_finishes_stop. Mutation: a failed replay slice skipsstop_vacates; the turn fails with "prefill cancelled".chat-session.test.ts, "a stop before the native stream starts changes nothing". Mutation: the cut is latched before the stop is accepted.chat-session.test.ts, "a stopped raw-replay turn keeps its reasoning block in the content". Mutation: the cut commit drops the raw reasoning block.engine::hybrid_scheduler::tests::a_vacated_stop_completes_beside_two_resident_qwen35_peersand..._qwen35_moe_peers. A preempted turn with 20+ generated tokens, a parked peer and a second resident peer holding both recurrent units, then a stop: done "stop" with the tokens it had, the full blocks through the cut still hit, both peers keep their rows. Mutation:finish_completedactivates the turn before it readsvacated_stop; the stop fails with the recurrent-unit cap error.Changed test:
interrupted_token_discards_partial_layer_state_and_can_restart. Its cancel half now interrupts a prefill, because a decode pass ends at its boundary.Gates, all at the final commit:
cargo fmt --all -- --checkcargo clippy --workspace --all-targets -- -D warnings--lib,RUST_TEST_THREADS=1yarn build:nativeindex.d.ctsmatches the crate copy; no codegen churnyarn typecheck,yarn tsc -b --forcevp lint --type-aware --type-check,vp fmt --check(9 touched TS files)vp test, 4 touched test filesvp test, 3 related server test filesReview round 1 (F1-F3), at the fix commit:
cargo fmt --all -- --checkcargo clippy --workspace --all-targets -- -D warnings--libengine::hybrid_scheduler/models::qwen4_exp,RUST_TEST_THREADS=1yarn typecheck,yarn tsc -b --forcevp lint --type-aware --type-check,vp fmt --check(touched TS files)vp testchat-session, qwen35-stream, messages-handlerReview round 2 (F4), at the fix commit:
cargo fmt --all -- --checkcargo clippy --workspace --all-targets -- -D warnings--libengine::hybrid_scheduler/models::qwen3_5::/models::qwen3_5_moe/models::qwen4_exp,RUST_TEST_THREADS=1models::qwen3::model::tests::a_stop_on_a_ragged_prefill_row_ends_as_a_completionNo model was loaded.
Gaps
usage.output_tokensis the nativenumTokens, which includes the overshoot. That is the step in flight plus the chunks already queued in the native mailbox, the N-API callback queue and the JS queue (64 deep each). Splash counts through the match token.vacateLane).stop_sequencesstay on the sync path. Splash streams every request.sendStream,sendToolResultStreamand the restart stream take no stop. No server caller uses them.ChatSessiondoes not commit. Native still registers the blocks./v1/responseshas no stop field.StopSearchalso matches inside thinking and tool-call text. mlx-node matches visible answer text only (S27's surface). Once this closes, S31 and stops interact.record_turn_mtp_acceptanceskips "cancelled"). The gate gets fewer samples, but no wrong sample.admit_preparedholds new turns back while a victim is preempted, so the fixture could not reach two resident peers beside a preempted turn through admission alone. The path where a stopped waiter is reaped (reap_cancelled_waiters) goes through the samefinish_completedarm.Not in this PR (live, not run)
max_tokens32,000.output_tokens≤ 200, and wall time ≤ 1/5 of the base.All three run against the base c0ce73b. The commands are in
LIVE.md.🤖 Generated with Claude Code