Repository navigation
fix(chat): preserve template continuation cache reuse - #109
Conversation
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_00cfa47a-e002-4163-851d-adb823629dbc) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 44c99994f3
ℹ️ 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".
|
Important Review skippedAuto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the ⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Plus Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
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. Comment |
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_e6348900-c7d3-4b44-8703-22b568e6cca7) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 586bd2eb69
ℹ️ 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".
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_9e3431f8-1b93-4cef-9916-fd961fe318fd) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 1f7898bf9a
ℹ️ 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".
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_949c6d17-5e66-4286-9e9a-152420537b44) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: facba4d8de
ℹ️ 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".
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_ee19c32f-58a5-4a77-9e22-ae173692d195) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 903245bc13
ℹ️ 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".
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_0ccb583e-e57c-4ec1-ba7f-5e3ddf10b8de) |
Bugbot couldn't run - usage limit reachedBugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit. A user or team admin can review and increase usage limits in the Cursor dashboard. (requestId: serverGenReqId_c85d2dd5-5500-4915-9bad-ac9c4a48e38a) |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3c2391578a
ℹ️ 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".
Merge-forward of mirror/upstream (237ab8a, tag v0.0.10). 10 upstream commits: mlx-node#108/mlx-node#109 template-authoritative chat + continuation cache reuse, mlx-node#110 desktop control panel, mlx-node#111 gemma4 long-context decode, mlx-node#113 quantized inference fast paths. NOT a low-risk bump. crates/mlx-sys/src/lib.rs (+93), mlx_na_int8.cpp (+162), mlx_paged_*.cpp/.h (~550), and mlx_paged_stubs_linux.cpp (+24, our platform) all move; build.mjs rebuilds mlx-sys as a cargo dependency, so this reaches the binary GenMLX loads. 7 conflicts, then 38 rustc errors from API ripples that auto-merged cleanly into regions our fork also touches. Three ripple classes: mlx-node#113 Embedding refactor — project_logits_from_hidden and the forward/prefill family now take `embedding: &Embedding` instead of a raw weight + optional transposed twin. Adopted wholesale. inject_image_placeholders — now returns Result<Vec<u32>>; fork VLM call sites needed `?` (16 of the 38 errors, and NO resolver reported this class). ChatStreamChunk — gained three required fields; fork-added literals filled by mirroring the dense sibling's own values rather than blind-defaulting. THE TRANSPOSED EMBEDDING WEIGHT WAS NEVER OURS. It was flagged mid-merge as a lost fork perf patch; provenance says otherwise. The merge base already carried it (69 dense / 42 MoE occurrences), traced to upstream's own mlx-node#24, and upstream removed it in mlx-node#113. Our fork merely FOLLOWED that convention at call sites we added. Preserving it would have been a regression, not a rescue: Embedding documents `get_weight()` as a tripwire — "production inference must never call get_weight() on a packed embedding because that constructs a full [vocab, hidden] dequantization graph" — and mlx-node#113's `as_linear` routes packed checkpoints through mlx_quantized_matmul(transpose=true) so the dense table is never materialized. FORK PATCHES VERIFIED INTACT: genmlx-d3yn (one generation stream per model) — byte-exact. Stream::new sites 4/4 dense and 2/2 MoE vs HEAD; generation_stream refs 90/90 and 80/80. This is the patch most at risk of silent loss, and note it CANNOT be validated here: the leak is Metal-only (Stream::new collapses to the default stream without Metal), which is why it never reproduced on Thor. A green battery on a CUDA box proves nothing about it. mlx-cft4 (merged_qkvz in MoE weight loading) — was HALF-LOST and is restored. Upstream demoted apply_weights_moe_inner to a #[cfg(test)] wrapper and moved production loading into apply_weights_moe_inner_with_residency, which had no merged_qkvz param; our parameter survived only on the test-only wrapper while its consuming logic rode into the production body. Re-plumbed (:522, consumed :765). Left unfixed this would have silently corrupted MoE expert weight loading — no test would have caught it. genmlx-uhtp (mlx_report_error on paged-attn catch sites) — intact, rebased onto upstream's renamed context label. mlx gitlink UNCHANGED (fef8890f both sides — no nax replay needed). Superset invariant re-verified on freshly fetched refs after finding the first check ran against a stale up/main: `git cherry -v origin/main fef8890f up/main` -> 0 '+'. cargo check -p mlx-core --release: 0 errors. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…e first Three review follow-ups on the preserve_thinking opt-in, no behaviour change. `enable_legacy_preserve_thinking` returns the template untouched as soon as it contains the substring `preserve_thinking`, and `enable_gemma4_preserve_thinking` inserts exactly that substring when it widens the gate spelling that lacks the flag. Legacy therefore has to run first, and nothing said so or checked it: swapping the two call lines silently disables the legacy rewrite with no compile error and no other test going red, because no shipped checkpoint carries both gate families. Add a unit test that drives the full render entry point over a template carrying both gates and asserts both rewrites landed. Verified: with the two calls swapped it fails `left: "GLG"` / `right: "LGLG"`, and it is the only test in the tokenizer module that notices (82 passed, 1 failed). The e2e `ar2.cached_tokens > 0` assertion exists to catch a regression that breaks BOTH lanes, so it must be read before the feature lane's own `sp2.cached_tokens > 0` — which sat ahead of it and tripped first, leaving the AR line never once observed red. Move it up to right after the AR turn completes, in both suites: with SESSION_PRESERVE_THINKING mutated to false, `dspark_stop_mid_block_then_delta_turn` now fails on "the AR baseline must warm-continue too (cached_tokens > 0), got 0". Also stop the render-context docs asserting a crate-wide invariant the crate does not hold. `preserve_thinking` is opt-in, but the sibling `keep_past_thinking` key is pinned ON for every caller, so lfm2-style thinking templates keep prior thoughts where transformers, mlx-lm and vLLM drop them. Pre-existing since 4fef3b3 (PR #109) and left alone here — the docs now name it as a known, tracked divergence instead of implying every one-shot render is byte-identical to upstream. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01MCBk7iwMve89ru8c116kki
…e first Three review follow-ups on the preserve_thinking opt-in, no behaviour change. `enable_legacy_preserve_thinking` returns the template untouched as soon as it contains the substring `preserve_thinking`, and `enable_gemma4_preserve_thinking` inserts exactly that substring when it widens the gate spelling that lacks the flag. Legacy therefore has to run first, and nothing said so or checked it: swapping the two call lines silently disables the legacy rewrite with no compile error and no other test going red, because no shipped checkpoint carries both gate families. Add a unit test that drives the full render entry point over a template carrying both gates and asserts both rewrites landed. Verified: with the two calls swapped it fails `left: "GLG"` / `right: "LGLG"`, and it is the only test in the tokenizer module that notices (82 passed, 1 failed). The e2e `ar2.cached_tokens > 0` assertion exists to catch a regression that breaks BOTH lanes, so it must be read before the feature lane's own `sp2.cached_tokens > 0` — which sat ahead of it and tripped first, leaving the AR line never once observed red. Move it up to right after the AR turn completes, in both suites: with SESSION_PRESERVE_THINKING mutated to false, `dspark_stop_mid_block_then_delta_turn` now fails on "the AR baseline must warm-continue too (cached_tokens > 0), got 0". Also stop the render-context docs asserting a crate-wide invariant the crate does not hold. `preserve_thinking` is opt-in, but the sibling `keep_past_thinking` key is pinned ON for every caller, so lfm2-style thinking templates keep prior thoughts where transformers, mlx-lm and vLLM drop them. Pre-existing since 4fef3b3 (PR #109) and left alone here — the docs now name it as a known, tracked divergence instead of implying every one-shot render is byte-identical to upstream. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01MCBk7iwMve89ru8c116kki
Summary
Root cause
PR #108 made checkpoint templates authoritative for full structured history. Re-rendering previously generated text is not token-lossless: BPE decode/re-encode can choose different token boundaries, and a length-truncated
<think>body cannot be reconstructed byte-for-byte by the template. That caused exact cache-prefix verification to miss and reset warm sessions. Older Qwen templates also dropped prior reasoning on the next user turn, while LFM templates require the raw assistant body incontent.After reconverting the original Qwen3.5 Hugging Face SafeTensors checkpoint, the formerly skipped MTP test exposed one additional issue: a warm suffix-only prefill has no full-prompt hidden seed, but the dense MTP stepper treated a zero position base as sufficient to enable committed-history/chained-cycle reuse. The warm path then diverged from the full-reprefill heal.
Validation
qwen3_5_paged_vs_flat_parity,qwen3_5_session,qwen3_5_delta_chat,p2_paged_thinking_honors_enable, andqwen3_5_cold_tier_paritymtp.*tensors@mlx-node/lmsuites passed (18 tests)yarn typecheckcargo clippy -p mlx-core --all-targets -- -D warningscargo fmt --all -- --checkgit diff --checkNote
High Risk
Changes core session KV reuse, multimodal cache identity, and MTP chained-cycle gating; incorrect verification could cause silent divergence or unnecessary cold replays.
Overview
Fixes warm chat session continuation so KV reuse no longer depends on re-rendering the full transcript into an exact token prefix match.
Live continuation path: On continue turns, the engine verifies completed structured history against the committed cache (including media payload identity via new
ChatBackendhooks and VLM placeholder collapse for comparison). When checks pass, it keeps cached token IDs and appends only the template-authored suffix (render_live_continuation), with fail-closed handling for reasoning-boundary whitespace and structuredreasoning_content. Successful splices mark turns as delta (profiler label,save_cache_state, skip re-feeding historical media).Compatibility & guards: Legacy Qwen templates get a narrow
preserve_thinkingrewrite; LFM models replayrawTextinmessage.contentviareplaysAssistantRawText. NAPI/session core reject new media on the pending continuation message before render. Dense Qwen3.5 MTP only enables committed-history / chained cycles when a full-prompt hidden seed exists (chained_cycles_supported).Tests: Broad engine, tokenizer, model, and
@mlx-node/lmcoverage for desync heal, media identity, expanded VLM history, and continuation behavior.Reviewed by Cursor Bugbot for commit 3c23915. Bugbot is set up for automated code reviews on this repo. Configure here.