Skip to content

fix(chat): preserve template continuation cache reuse - #109

Merged
Brooooooklyn merged 7 commits into
mainfrom
fix/e2e-template-continuations
Jul 31, 2026
Merged

Brooooooklyn merged 7 commits into
mainfrom
fix/e2e-template-continuations

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • preserve exact committed token IDs for live continuations while appending only the suffix authored by the checkpoint chat template
  • fall back to a cold full-history replay when the structured history was edited or cannot reproduce the live cache
  • keep legacy Qwen reasoning history and LFM assistant replay compatible with their checkpoint templates
  • reject continuation media changes with the typed restart error before template rendering
  • require an actual full-prompt hidden-state seed before dense Qwen3.5 MTP enables committed-history and chained-cycle reuse

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 in content.

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

  • exact Qwen3.5 CI model matrix passed: qwen3_5_paged_vs_flat_parity, qwen3_5_session, qwen3_5_delta_chat, p2_paged_thinking_honors_enable, and qwen3_5_cold_tier_parity
  • Qwen3 paged/flat reuse target passed (2 tests)
  • LFM paged/flat parity passed (9 tests) and LFM session target passed (12 tests)
  • Qwen3.5 MTP integration target passed all 9 tests with a checkpoint containing all 15 mtp.* tensors
  • engine MTP unit tests passed (23), engine command/session tests passed (27), and tokenizer tests passed (36; 2 model-gated tests ignored)
  • targeted @mlx-node/lm suites passed (18 tests)
  • yarn typecheck
  • cargo clippy -p mlx-core --all-targets -- -D warnings
  • cargo fmt --all -- --check
  • git diff --check

Note

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 ChatBackend hooks 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 structured reasoning_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_thinking rewrite; LFM models replay rawText in message.content via replaysAssistantRawText. 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/lm coverage 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.

@Brooooooklyn
Brooooooklyn marked this pull request as ready for review July 31, 2026 07:40
@cursor

cursor Bot commented Jul 31, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot 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)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread crates/mlx-core/src/engine/session.rs Resolved
@Brooooooklyn Brooooooklyn added the model-e2e Run the heavy Model E2E workflow (per-family real-checkpoint tests) on this PR label Jul 31, 2026
@coderabbitai

coderabbitai Bot commented Jul 31, 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

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 990e5bd0-eeb4-4686-9f3f-53b4d00e6885

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

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

Comment @coderabbitai help to get the list of available commands.

@cursor

cursor Bot commented Jul 31, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot 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)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread crates/mlx-core/src/engine/session.rs Resolved
@cursor

cursor Bot commented Jul 31, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot 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)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread crates/mlx-core/src/engine/session.rs Resolved
@cursor

cursor Bot commented Jul 31, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot 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)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread crates/mlx-core/src/engine/session.rs Resolved
@cursor

cursor Bot commented Jul 31, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot 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)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread crates/mlx-core/src/engine/session.rs Resolved
@cursor

cursor Bot commented Jul 31, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot 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)

@cursor

cursor Bot commented Jul 31, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot 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)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

@Brooooooklyn
Brooooooklyn enabled auto-merge (squash) July 31, 2026 10:59
@Brooooooklyn
Brooooooklyn merged commit 4fef3b3 into main Jul 31, 2026
10 checks passed
@Brooooooklyn
Brooooooklyn deleted the fix/e2e-template-continuations branch July 31, 2026 11:04
robert-johansson pushed a commit to robert-johansson/mlx-node that referenced this pull request Aug 2, 2026
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]>
Brooooooklyn added a commit that referenced this pull request Aug 21, 2026
…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
Brooooooklyn added a commit that referenced this pull request Aug 21, 2026
…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
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