Skip to content

feat: Control Panel redesign, Chat/Work, Flash Next fixes, Qwen3.5 scheduler on by default - #382

Closed
Brooooooklyn wants to merge 347 commits into
codex/issue-142-gemma4-benchmarkfrom
feat/app-redesign-uiarc
Closed

Brooooooklyn wants to merge 347 commits into
codex/issue-142-gemma4-benchmarkfrom
feat/app-redesign-uiarc

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

One branch with 17 commits, on main after #378 (the DFlash2 state disk tier) and #383.

Area What
packages/server Turn traces and runtime samples (metadata only), measured prefill (prefillMs / prefillTokens), POST /v1/models/unload, GGUF model naming with quantization variants, a turn reports where it waits (queued / slot / prepare / prefill / decode), a tool call that misses its one object argument gets it rebuilt, a thinking budget with a cycle guard and an end text on the agent hosts
packages/desktop Control Panel host changes: folder dialog for Work, endpoint file fields, bundled skills. MAIN judges Control Panel liveness by ping; a slow page call no longer restarts the Control Panel
packages/dashboard Control Panel redesign on the free Arc components (MIT) plus own components; Chat / Work over ACP; permission modes Ask / Auto / Bypass; Web Search providers (keys in the macOS Keychain); Agent timeline; waiting orb; load card with the kernel warm-up; a Work turn continues once after a length stop
qwen4_exp Flash Next: tool calls parse (tokenizer special flags), the prefill window stays 1,024 rows on a partial expert store, a follow-up turn reuses its prefix to a message boundary, drafts after a restore, restore after a restart
qwen3_5 The scheduler is on by default for Qwen3.5 dense and MoE with no env; the lane count comes from the memory plan (up to 4, up to 8 from 256 GB); MoE MTP lanes keep their lone tokens; MTP norm shift rule
engine Thinking cycle guard and end text; load-time warm-up of the scheduler's pipelines; stream progress phases and wait timers; the paged-attention metallib loads from memory (no temp file)

Behaviour changes

  • MLX_CONTINUOUS_BATCHING is gone. MLX_SERVE_FORCE_SERIAL=1 is the one rollback.
  • Qwen3.5 lanes: plan one lane, then grant the most lanes that keep that context window. Lanes give way before the window. The lane table is pinned with the state tier off and on; with the tier on, one GDN cell of staging moves five memory-bound rows (for example 9B AR at 16 GB: 2 lanes to 1).
  • Qwen3.5 0.8B: the MTP norms were read as shifted and the MTP head accepted no draft. One decision for the whole MTP module from four norms. Only the 0.8B checkpoints change their decision.
  • Qwen3.5 dense / MoE loads on the scheduler run a warm-up before they serve (scratch turns per lane count and row class). The model state, the block pool, the governor books and the state tier read as before. A failed step fails the load.
  • Disk cache: the desktop engine, mlx agent and mlx serve use the mechanism of main. Qwen3.5 persists DFlash2 states in the per-model state tier. The whole-prompt capture of this PR (persistWholePrompt, on for the desktop engine and mlx agent) applies to the per-turn families only (Qwen3, Gemma4, Muse-Glimmer, LFM2). The refused-rung booking of an earlier head is dropped, because main deleted refused rungs.
  • A Qwen3.5 trace row carries stateTier (persistent / temp / off); the Cache page counts such a turn by it. coldEnabled keeps its meaning (the process tier).
  • Flash Next: <tool_call>, </tool_call>, <think>, </think> are no longer special tokens; the asset cache identity is bumped, so the tokenizer sidecar is rebuilt once. Its prefix states and KV blocks go to the process disk tier and restore after a restart.
  • New napi surface: ChatConfig.thinkingCycleGuard / thinkingEndText; reasoningClose / reasoningCutAt / reasoningCyclePeriod / reasoningStrayCloses on the result and the done chunk; ChatStreamProgress.phase (6 values) with waitMs / slotMs / prepareMs; WarmupReport, LoadProgress, loadProgress(path), pipelineStats(), the warmup getter.
  • Control Panel recovery: the page can no longer ask for a restart; a call with no reply fails alone with E_TIMEOUT. MAIN pings every 5 s and restarts the panel after 30 s of silence (120 s when a turn runs). A stuck database worker restarts alone. Each recovery writes metadata rows to ~/.mlx-node/ledger/.

Test plan

  • cargo test -p mlx-core --lib (scoped: engine, model_thread, tokenizer, tools, paged KV adapter, qwen3, qwen3_5, qwen4_exp, memory_plan, disk_tier, cold_tier): 2049 passed; 0 failed; 95 ignored
  • cargo test -p mlx-paged-attn --lib: 222 passed; 0 failed; 8 ignored; cargo test -p mlx-metal --lib: 6 passed
  • cargo clippy -p mlx-core -p mlx-metal -p mlx-paged-attn --all-targets -- -D warnings, cargo fmt --all -- --check
  • yarn build:native (full profile), both index.d.cts copies in sync
  • yarn build:ts, yarn typecheck, vp lint --type-aware --type-check on the touched files, UI build, pack test
  • vp test (dashboard, server, desktop, agent, lm, cli, __test__/server, __test__/cli): Test Files 314 passed | 3 skipped, Tests 7058 passed | 15 skipped
  • Qwen3.5 0.8B, real weights, persistent state tier in a throwaway cache dir: warm-up 55 steps, 0 skipped; the tier holds no state after the load; a thinking turn with budget 64 closes by budget with the end text and a non-empty answer; the next turn reuses the prefix past the close
  • One Qwen3.5 0.8B dense parity test on real weights on the rebased base: 1 passed
  • Not run: the warm-up on real 27B / MoE geometry, MoE parity on a real checkpoint, the Flash Next live check on this base, the Control Panel recovery on a real Electron process, __test__/cli/agent-e2e

Known limits

  • MoE scheduled MTP with 2 or more lanes is not bit-exact against one lane alone (batch-shape rounding). AR is exact.
  • The first turn can still compile a pipeline that takes the prompt length as a build-time constant (qwen4_window_conv, qwen4_gdn_prepare under 64 rows).
  • The warm-up also runs on mlx eval and FP8 calibration loads (load time only).
  • With sampling on, a lowered thinking budget changes the MTP draft cap, so the sample path before a cut is not equal to a run without the guard. Greedy decode is exact.
  • A Flash Next state costs about 110 MiB; states use spare budget only. Flash Next keeps its own disk objects beside the state tier.
  • The Auto /tmp rule ships as built by owner decision.

🤖 Generated with Claude Code

https://claude.ai/code/session_01LJdkgMbCXHf4khtrZCVNPB

Brooooooklyn and others added 30 commits June 26, 2026 09:55
…79)

## Problem

Main CI intermittently fails on a single Rust unit test (most recently
on the PR #78 merge commit, run `28209793148`):

```
FAILED: nn::losses_test::tests::test_cross_entropy_qwen3_vocab
        crates/mlx-core/src/nn/losses_test.rs:630
        "Loss should be > 10.0, got 9.881153"
        (1868 passed, 1 failed)
```

It is **unrelated to whatever PR happens to be merging** — the test was
last touched in #12 and only `convert.rs` changed in #78. It is a
pre-existing flaky test.

## Root cause

The test builds random logits/targets with **no seed** and asserts a
tight band on the mean-reduced loss:

```rust
logits  = random_normal([2, 151936], 0,1, None)   // None is the DTYPE arg, not a seed
targets = randint([2], 0, 151936)
loss    = mean_over_batch( logsumexp(logits) − logits[target] )   // ≈ log(151936) ≈ 11.93
assert!(10.0 < loss < 15.0)
```

With `batch_size = 2`, the loss is `≈ 12.43 − N(0, 0.71)` — a high
random target logit occasionally drags the mean below `10.0` (the
observed `9.88` is a ~3.5σ draw).

## Fix

Bump `batch_size` 2 → 64. The mean-reduction then concentrates the loss
at `log(V)`, shrinking the spread from ±0.71 to ±0.13. Vocab is
unchanged, so the large-vocab **chunking path is still exercised**.

### Verification (2,000,000-draw simulation of the exact loss model)

| batch | loss | min | P(loss<10) | P(loss>15) |
|------:|------|----:|-----------:|-----------:|
| 2 | 12.43 ± 0.71 | 9.01 | **0.030%** | 0.015% |
| 64 | 12.43 ± 0.13 | 11.82 | **0** | 0 |

At batch=64 the loss stays in `[11.8, 13.0]` across 2M draws — ~15σ from
the `10.0` bound. (`logsumexp` constant measured = 12.4313, matching
`ln(V)+0.5`.)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Test-only change with no production or loss-implementation edits;
slightly more work per test run from a larger batch.
> 
> **Overview**
> Stabilizes **`test_cross_entropy_qwen3_vocab`** in `losses_test.rs` by
raising **`batch_size` from 2 to 64** while keeping the Qwen3-sized
vocab (151936) and the same `(10.0, 15.0)` loss band.
> 
> The test still uses unseeded random logits/targets; with a tiny batch,
a lucky target logit could drag the mean cross-entropy below 10.0 and
fail CI. A larger batch tightens the mean-reduced loss around
`log(vocab)` so the assertion is reliable without changing what the test
exercises (large-vocab / chunked cross-entropy path).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
0225f73. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Opus 4.8 <[email protected]>
…mbed, compressed-position decode + delta lifetime) (#80)

## Summary

Fixes **Qwen3.5-VL image inference** for both the `qwen3_5` (dense) and
`qwen3_5_moe` families. Before this branch, an image turn ran end-to-end
but
produced garbage descriptions — the model could not read text and
hallucinated
unrelated subjects (e.g. described a bank-reconciliation table as "dark
grey
stone / white fabric"). Text inference and `mlx convert` were
unaffected; only
the visual-feature path was wrong.

Found via `ornith-1.0-35b` (a Qwen3.5-VL-MoE-35B-A3B post-train).
Root-caused by
numeric bisection against the reference `mlx-vlm` implementation.

## Root causes & fixes (all verified vs `mlx-vlm`)

1. **Interleaved multimodal RoPE for image tokens** (`fb95c6d8`)
Qwen3.5-VL uses the **interleaved** (stride-3 per-freq) M-RoPE selector,
not
the PaddleOCR **sectioned/contiguous** one. Text tokens (`t==h==w`) are
identical either way — which is exactly why text always worked while
images
(`t≠h≠w`) got the wrong rotation axis on ~17% of frequencies, every
attention
   layer, destroying the 2D positional structure.

2. **Patch embedding: sum Conv3d temporal slices + load
`patch_embed.proj.bias`** (`6a889bdb`)
The patch embed previously used only the first temporal slice and
hard-coded
   the conv bias to `None`.

3. **Decode rotates at the compressed M-RoPE position** (`b5c4420e`)
Image prefill compresses ~754 placeholder tokens into ~29 M-RoPE
positions, so
`rope_deltas = max_position + 1 − seq_len` (≈ −726). Decode must rotate
the
query at `physical_slot + rope_deltas` while K/V still writes at the
physical
   slot. Threaded a `rope_position_offset: i32` through
`forward_paged` / `decoder_layer` / `paged_forward` (dense + MoE share
one
`forward_paged`); the negative delta is carried on
`VisionMerge.rope_deltas`
and stored in `cached_rope_deltas` at VLM prefill. The physical position
is
   cast `u32 → i32` **before** the negative add to avoid underflow.

4. **rope-delta lifetime gate** (`f7ae00ca`)
Found by adversarial review of (3). The cross-turn delta was reset only
when
   `cached_prefix_len == 0`, but the paged-turn planner also yields
`cached_prefix_len > 0` with `continued_live_prefix == false` on a
**non-live
prefix-cache hit**. Because the model instance is shared across all
sessions,
a stale negative delta from a prior image turn could then leak into an
unrelated **text-only** request that merely shares a cached text prefix
—
   rotating that text at `physical + stale_delta` → garbage.

Factored the decision into
`rope_delta_for_paged_turn(cached_rope_deltas,
continued_live_prefix)` (keep the delta iff it is a live image
continuation,
else clear) and wired it through all six paged reset gates (dense + MoE
×
sync / stream / engine). This is safe because image requests prefill
with
`skip_lookup` and never publish a hashable text stream that collides
with
their expanded-placeholder blocks, so every non-live hit restores only
pure-text prefix blocks (delta 0); only a live continuation re-attends
the
image's compressed-position K/V. Added three model-free lifecycle
regression
   tests.

5. **e2e correctness gate** (`ab044b88`)
`qwen3_5_moe_vl_reads_document_text` and `qwen3_5_vl_image_chat.rs`
(dense) —
   `#[ignore]`, env-gated (`MLX_TEST_QWEN35MOE_VL_MODEL_PATH` +
`MLX_TEST_VLM_IMAGE_PATH`), asserting the model reads ≥2 `DOC_KEYWORDS`
from
`examples/ocr.png`. These are the ground-truth gates for VL image
inference.

### Note on the addmm commit (`12e89b3a` + `8e6d69d9`)

`12e89b3a` replaced the fused `mlx_array_addmm` primitive with an
explicit
`matmul + add`, originally attributed to a bug in `mlx::core::addmm`.
**That
premise was wrong** — PyPI MLX's `addmm` applies the `C` term correctly
(maxdiff 0) and the FFI wrapper passes its arguments correctly. The real
cause
was a corrupt local metallib that miscompiled the fused GEMM kernels
(the same
bad build also miscompiled the NAX gemm). The explicit form is kept as
robustness against this project's documented non-deterministic metallib
corruption — it is correctness-equivalent and vision/bias-only so the
perf cost
is negligible — and the `nn::linear` C-application tests double as a
build
canary. `8e6d69d9` corrects the misleading comment so it no longer
claims an mlx
source bug.

## Validation

- **e2e READS-DOC** on the mxfp8-converted `ornith-1.0-35b` checkpoint:
the model
  reads the document, matching all 7 keywords
  (`reconciliation, bank, council, trunch, october, 2019, balance`).
- `nn::linear` addmm/bias tests, `paged_forward` rope-offset +
delta-lifetime
  tests, and the broader rope/m-rope/delta unit sweep (70 tests) pass.
- `cargo clippy -p mlx-core --all-targets -D warnings` clean; `cargo
fmt` clean.
- Adversarial review of the branch: **approve, no material findings**.

> The full `cargo test -p mlx-core --lib` (debug) shows pre-existing
Metal-f32
> failures (banded-attn / attention-vjp) plus a few cross-family
numerical tests
> that fail only against the corrupted local **debug** metallib; all of
them pass
> in release against a correctly-built metallib (and reproduce on
`main`), so the
> branch introduces no new failures.

## Test plan

```bash
# unit (release, correct metallib)
cargo test --release -p mlx-core --lib -- nn::linear paged_forward rope delta

# e2e image-correctness (env-gated, sequential — large models)
MLX_TEST_QWEN35MOE_VL_MODEL_PATH=<converted-qwen3.5-vl-moe> \
MLX_TEST_VLM_IMAGE_PATH=$PWD/examples/ocr.png \
  cargo test --release -p mlx-core --test qwen3_5_moe_vl_image_chat -- \
  --ignored --nocapture qwen3_5_moe_vl_reads_document_text
```

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Changes core attention RoPE, vision weights, and shared paged
inference state across dense/MoE VL; incorrect delta lifetime or offset
math would corrupt multi-turn or cached-prefix text, though extensive
unit and env-gated e2e tests mitigate this.
> 
> **Overview**
> Fixes **Qwen3.5-VL image inference** (dense and MoE) by aligning
vision, RoPE, and paged decode with `mlx-vlm`.
> 
> **Interleaved M-RoPE** — Adds
`apply_multimodal_rotary_pos_emb_interleaved` and switches Qwen3.5
attention from the PaddleOCR sectioned apply so image tokens get
stride-3 per-frequency axis selection; text-only paths stay unchanged
via invariance tests.
> 
> **Vision tower** — `addmm` is implemented as explicit `matmul` +
scaled add (avoids local metallib fused-GEMM corruption that dropped
biases). Patch embed loads optional conv bias and collapses Conv3d
weights by summing temporal slices instead of taking slice 0.
> 
> **Compressed M-RoPE decode** — `VisionMerge` carries `rope_deltas`;
`get_rope_index` uses the global max over t/h/w axes. Paged
prefill/decode/MTP thread `cached_rope_deltas` through
`paged_rope_offset` and `rope_position_offset` so rotation uses
compressed positions while KV stays at physical slots.
`rope_delta_for_paged_turn` keeps the delta only on
`continued_live_prefix` so stale image deltas do not leak into unrelated
text prefix-cache hits.
> 
> **Tests** — Unit tests for interleaved RoPE, rope offset/delta
lifecycle, patch embed, linear bias; env-gated e2e `reads_document_text`
gates for dense and MoE VL.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8e6d69d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
…tition cutoff (#81)

## Why

Running `mlx launch claude` against a local MLX model surfaced two
server-side defects:

1. **Claude Code's auto-mode safety classifier always sends
`stop_sequences`.** The
`/v1/messages` mapper rejected any request carrying `stop_sequences`
with a `400`, so the
classifier failed with *"temporarily unavailable, cannot determine
safety of Agent"* and the
   agent stalled.
2. **The native anti-repetition cutoff truncated legitimate output.** A
wide ASCII box border
(`────`), a separator (`====`/`----`), a table rule, or repeated
indentation tripped the
default cutoff (`maxConsecutiveTokens=16`, `maxNgramRepeats=3`),
returning
`finish_reason:"repetition"` → mapped to `end_turn` — so answers were
silently cut off
   mid-diagram and looked like a clean finish.

## What

- **Honor `stop_sequences` end-to-end in `/v1/messages`** (streaming +
non-streaming): detect,
truncate exactly, and report `stop_reason:"stop_sequence"` +
`stop_sequence`. Removes the 400.
- **Loosen the Qwen anti-repetition cutoff** in the launch presets (`256
/ 8 / 64`) so wide
  boxes/tables/separators survive while a true runaway loop still stops.

TS-only in `packages/server` — **no native/Rust change**,
`ChatConfig`/`packages/core` untouched.

## How

- `StopSequenceBuffer` (`packages/server/src/stop-sequence-buffer.ts`) —
cross-delta detection
mirroring `ToolCallTagBuffer`: partial-suffix holdback so a stop split
across two streamed
deltas is caught; earliest-match-wins, longest-on-tie (including a
longer stop that begins at
an earlier index); whitespace-only and empty stops filtered to a no-op.
- Request/response mappers thread `stopSequences` and can emit
`stop_reason:"stop_sequence"` (precedence over
`max_tokens`/`tool_use`/`end_turn`).
- Streaming done-path uses **suppress-then-natural-done**: it keeps
consuming to the native
`done` chunk (commit gate + history commit still fire), and finalizes
the stop scan over one
continuous buffer — streamed deltas, the held partial, tag residue, and
the recovered terminal
text — **before** emitting the safe prefix, deciding tool-call emission,
or computing
`stop_reason`. A matched stop suppresses any `tool_use` block so a
response never carries both
a tool call and `stop_reason:"stop_sequence"`. Empty/absent
`stop_sequences` is a byte-identical
  no-op.
- Presets (`packages/server/src/presets.ts`): all four
`QWEN_SAMPLING_DEFAULTS` variants get
`maxConsecutiveTokens:256, maxNgramRepeats:8, ngramSize:64`. Gemma4/LFM2
unchanged.

## Testing

- `__test__/server/` — **24 files, 688 tests pass** (incl. new buffer,
mapper, and handler
coverage; the original 400-asserting tests replaced with honor-behavior
tests).
- TDD throughout (failing test first), then 4 adversarial review rounds
(Codex); every confirmed
finding fixed and re-verified by execution. The one remaining review
note (an overlap edge that
would only bite if the native terminal chunk were *incremental*) was
verified non-occurring —
`backend.rs` `finish()` sends the full cumulative `result.text`
(`clean_text`), which the
  overlap logic is built for.
- `vp lint --type-aware --type-check` and `yarn typecheck` clean.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Large changes to Anthropic message streaming/non-streaming output
shaping and stop/tool precedence; behavior is heavily tested but
regressions could affect wire format or truncation edge cases.
> 
> **Overview**
> **`/v1/messages` now honors Anthropic `stop_sequences` instead of
returning 400.** The request mapper normalizes stop strings (filters
empty/whitespace-only) and returns them as `stopSequences` beside
`ChatConfig`, which has no native stop field. A new
**`StopSequenceBuffer`** detects matches across streamed deltas (partial
holdback, earliest/longest tie-breaks) and drives truncation plus
**`stop_reason: stop_sequence`** and **`stop_sequence`** on responses
and SSE **`message_delta`**. Streaming and non-streaming paths wire the
buffer through tool-tag buffering, terminal recovery, and flush-at-end;
a matched stop **suppresses `tool_use`** blocks so stop wins over tools.
Absent stops remain a pass-through no-op.
> 
> **Qwen launch presets** add loosened anti-repetition sampling
(**`maxConsecutiveTokens: 256`**, **`maxNgramRepeats: 8`**,
**`ngramSize: 64`**) on all four **`QWEN_SAMPLING_DEFAULTS`** variants;
Gemma4/LFM2 unchanged. Tests cover buffer, mappers, handler edge cases,
and preset merge survival.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
ee1e456. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
## Problem

Qwen models generating large markdown tables (a
`|----------------------------------|` rule, or many byte-identical
rows) get **silently truncated**. The native `check_repetition_cutoff`
runs every decode step and stops generation on N identical tokens in a
row (Tier 1) or a repeating n-gram block (Tier 2). It fires on
legitimate repeated structure — table rules, ASCII boxes, separators,
repeated rows — and the `"repetition"` finish reason is then mapped to a
clean `end_turn`, so the cut looks like a normal answer.

PR #81 only loosened the **TS Qwen launch preset** (256/8/64). Every
other path — non-launch servers, Gemma4/LFM2, per-request configs that
omit the fields, and the napi `GenerationConfig::default()` — still fell
back to the tight native defaults (16/3/64), so as few as ~6 repeated
tokens still truncated tables.

## How vLLM handles it (the model for this change)

vLLM ships **no** repetition-stop heuristic by default. It shapes
repetition only with logit-level penalties (`repetition_penalty` 1.0,
`frequency_penalty`/`presence_penalty` 0.0 — all no-ops by default) and
stops generation only on real conditions (EOS, stop tokens, stop
strings, `max_tokens`). Its opt-in loop detector
(`repetition_detection`, recent main) defaults to `None`, and when
enabled surfaces its own distinct `FINISHED_REPETITION` finish reason
rather than disguising the cut.

## Change: fully align with vLLM — cutoff OFF by default, opt-in

- **`fix(sampling)`** — Introduce three named constants (all `0`) in
`sampling.rs` and route **every** former 16/3/64 default-fallback site
through them (`params.rs`, qwen3 / qwen3.5 / qwen3.5-MoE / gemma4 /
qianfan_ocr model files, and the napi `GenerationConfig::default()`).
With the knobs unset the detectors resolve to disabled (`0` already
trips the existing `check_consecutive` / `check_ngram` guards). The
detection **algorithm is unchanged**; GRPO training (`grpo/engine.rs`)
and paddleocr keep their explicit values. New unit tests lock
default-off and prove a positive value still re-enables detection
(opt-in).
- **`fix(server)`** — Remove the now-unnecessary loosened cutoff
(256/8/64) from all four Qwen launch presets; repetition is now shaped
by the sampling penalties and bounded by `maxOutputTokens`, with
per-request opt-in still winning via `ChatSession.mergeConfig`. Presets
test flipped to assert the fields are absent while keeping the
opt-in/override coverage.
- **`fix(types)`** — Sync the build-generated
`packages/core/index.d.cts` cutoff doc comments to match the hand-synced
`crates/mlx-core/index.d.cts` (both now say `default: 0 = disabled`),
and rename a stale test `describe` block.

### Behavior change / migration

A degenerate small model now runs to `max_tokens` (default
`max_new_tokens` = 2048) instead of stopping at ~16 tokens. This is
intended and vLLM-aligned — `max_tokens` is the backstop. Operators who
want the old early repetition-stop must now set `maxConsecutiveTokens` /
`maxNgramRepeats` / `ngramSize` explicitly (per-request or via
registered `samplingDefaults`).

## Testing

- Rust: `cargo test -p mlx-core --lib repetition` → 28 passing (TDD
RED→GREEN; algorithm tests unchanged). Full lib suite 1878 pass; the 7
failures are pre-existing flaky f32/Metal numerical tests (banded-attn,
attention-vjp, packed-affine embedding, sparse-moe gather,
chunked-prefill parity) — verified to fail identically on base
`73f4a89e`, no path to this change.
- TS: `vp test __test__/server/presets.test.ts` → 7/7.

## Out of scope (noted, not fixed here)

An adversarial review flagged that `/v1/responses` never clamps
`max_output_tokens` against the registry's per-model `outputTokenLimit`
(unlike `/v1/messages`). Independently verified as **pre-existing**
(byte-identical at base `73f4a89e`; this branch doesn't touch
`responses.ts`/`messages.ts`) and **not** a regression of this change
(the cutoff only ever caught exact-repeat loops, never bounded long
coherent output). Worth a separate server-hardening PR.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes default generation stopping behavior across all chat paths:
legitimate long repeats no longer truncate early, but runaway loops rely
on `max_new_tokens` unless operators opt back in via config.
> 
> **Overview**
> **Native repetition-stop heuristics are off by default**, matching
vLLM: unset `maxConsecutiveTokens`, `maxNgramRepeats`, and `ngramSize`
now resolve to **0** (disabled) instead of 16/3/64. Shared `DEFAULT_*`
constants in `sampling.rs` replace scattered literal fallbacks across
chat param extraction and Qwen/Gemma/Qianfan generation paths; the
detection logic is unchanged and **positive per-request values still opt
in**.
> 
> **Qwen launch presets** drop the previous 256/8/64 “loosened” cutoff
pins—repetition is left to sampling penalties and `maxOutputTokens`,
with `ChatSession.mergeConfig` still letting clients override. **API
docs** (`ChatConfig` / `GenerationConfig`) and **tests** (presets,
`params.rs` unit tests, LFM2 session comment) are updated for
default-off behavior.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5686106. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
…LX NAX-fork bump, metallib packaging hardening) (#83)

## What & why

Implements the *inference perf polish + quality sweep* design spec: a
correctness pass over the shared inference paths, a vendored-MLX bump
that fixes broken Apple-Silicon (gen-17 / M5) kernels, and a
code/comment cleanup sweep. 48 commits on top of `main` (`f65104aa`).

## Highlights

**Correctness**
- **qwen3.5 scalar RoPE axis fix** — the scalar RoPE arm fed `[B,T,H,D]`
to `fast::rope`, rotating along the **head** axis instead of the
**token** axis (rotation angle was constant across tokens). This is the
*production* path (dense / MoE / MTP / VLM-text, flat + paged), so every
qwen3.5 output changed. Fixed by transposing to `[B,H,T,D]` → rope →
back, matching mlx-lm. Self-referential gates never caught it; added an
absolute regression test.
- **sym8 flat-KV pins (dense + MoE)** — a sym8 checkpoint emits
mixed-dtype K/V (f32 K after the f32-weight `k_norm`, bf16 V) which the
block-paged pool rejects on the first write. Both loaders now pin sym8
to the validated flat path.
- gemma4-prequant `group_size` metadata honesty; qwen3.5-MoE loader
`ensure_dense_weight_floating` guards so packed weights with missing
sidecars fail loud.

**Vendored MLX bump** (`crates/mlx-sys/mlx`)
- Bumped to a **fork branch** `nax-macos-26-0-floor` @ `de7e3429` =
upstream `ml-explore/mlx` `e9463bbfc` + one cmake patch. The old pin's
NAX kernels were **broken on gen-17 / macOS ≥ 26.2** (bf16 unaligned-K
GEMM, bf16 causal full-SDPA, sorted `gather_mm` all producing garbage;
f32 sorted `gather_mm` SIGABRT). Three of four classes are fixed and
probe-verified; the fourth (f32 TF32 degradation) is upstream's
deliberate `MLX_ENABLE_TF32=1` default, kept as-is with a documented
escape hatch.
- The one fork patch adds `option(MLX_METAL_FORCE_NAX)` so npm artifacts
keep a **macOS 26.0** load floor while still shipping the NAX kernels
(compiled at their required 26.2 ABI; runtime `is_nax_available()` gates
dispatch at 26.2+). Upstream's 26.2 gate turned out to be a
*correctness* gate — building NAX at a uniform 26.0 target miscompiles.
- Submodule URL is the public HTTPS fork; the pinned commit is on a
pushed branch, so CI submodule checkout works.

**Packaging hardening** (`packages/core`)
- metallib selection is now bound to the built `.node`'s baked
`METAL_PATH` (authoritative, not an mtime heuristic), byte-compared to
the install copy, deployment-floor-gated, and **fails closed in
publish/release mode** (`MLX_METALLIB_STRICT=1` in CI). Closes a
long-standing "stale/incomplete metallib" hazard (root-caused to
stale-dir first-match pairing, not a corrupt build).

**Cleanup** — retired dead compiled-C++ comments/docs across qwen3.5
dense+MoE, canary-gated the tests that depend on the (now-fixed) NAX
kernels, plus assorted comment/hygiene fixes.

## Testing

- Rust: `mlx-core` lib **1930/0** (46 ignored), `mlx-paged-attn`
**220/0**, clippy `-D warnings` clean, `cargo fmt` clean.
- TS: `yarn typecheck` clean, metallib-select **45/45**, full Vitest
suite green apart from a missing gitignored GSM8K fixture and 4 gemma4
real-model E2E tests (see caveat).
- Every high-risk area passed an independent adversarial review pass;
the packaging series went through several review rounds.

## Perf — new-pin decode (no regression; modest gains)

Full cooled re-bench on **M5 Max (gen-17)** through a fresh new-pin
binary — both published 35B `qwen3_5_moe` series, every quant, median of
3×512-token greedy decodes with a 60-second GPU cooldown after every
generation. tok/s, vs each model's previously-published (old-pin)
number:

| quant | Ornith-1.0-35B old→new (Δ) | Qwen-AgentWorld-35B-A3B old→new
(Δ) |
|---|---|---|
| UD-Q3 | 103.8 → **111.6** (+7.5%) | 105.8 → **112.3** (+6.1%) |
| UD-Q4 | 87.0 → **102.3** (+17.6%) | 94.5 → **99.8** (+5.6%) |
| UD-Q5 | 91.2 → **95.4** (+4.6%) | 90.8 → **95.4** (+5.1%) |
| UD-Q6 | 87.1 → **93.1** (+6.9%) | 88.2 → **92.7** (+5.1%) |
| UD-Q8 | 84.2 → **91.5** (+8.7%) | 64.3 → **91.1** (+41.7%)\* |
| MXFP4 | 90.1 → **107.8** (+19.6%) | 85.7 → **102.6** (+19.7%) |
| NVFP4 | 87.8 → **94.6** (+7.7%) | 77.1 → **94.1** (+22.0%) |
| MXFP8 | 80.0 → **84.8** (+6.0%) | 62.4 → **91.0** (+45.8%)\* |
| BF16 | 56.5 → **62.8** (+11.2%) | 41.8 → **60.8** (+45.5%)\* |

All 18 models coherent (per-model warm-up read). **No quant regressed**
— the RoPE fix's added transposes cost no measurable decode throughput.
The reliable branch signal is roughly **+5–22%** across the
cool-baseline quants.

`*` The three outsized AgentWorld deltas are dominated by **old-pin
thermal crush** — those prior numbers were measured hot at a sequence
tail (~62–64 tok/s) — not a genuine pin speedup. The new cooled numbers
restore correct size ordering and match Ornith's siblings. Separately,
**Gemma-4-26B-A4B** (gemma4, bump-only) landed ~55–60% above its M3-Max
baseline in an earlier sanity bench (host-mismatched, directional only).

Both collections' published HuggingFace model cards were regenerated
with these numbers.

## Caveat for the first build

The branch's packaging changes are TS-only and did not rebuild the
native addon, so the checked-in dev artifacts are still the old pin. The
**first `yarn build:native`** (locally or in CI) deploys a fresh new-pin
addon + metallib — the 4 gemma4 E2E tests fail only because they
currently run against that stale old-pin addon and go green once it's
refreshed. Validate that first build against the metallib integrity gate
(now enforced by strict mode).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes affect published macOS binary compatibility (26.0 floor),
release metallib fail-closed behavior, and several inference/quant paths
(sym8 MoE, decode cache cadence, privacy-filter memory); mitigated by
extensive new tests but release impact is real.
> 
> **Overview**
> CI and docs now **pin `MACOSX_DEPLOYMENT_TARGET=26.0`** and
**`MLX_METALLIB_STRICT=1`** for the whole workflow so builds and tests
match published npm darwin-arm64 artifacts (26+ load floor, fail-closed
metallib gates). **README** states prebuilt binaries require macOS 26+
and explains NAX kernel runtime gating.
> 
> **Metallib packaging** gains a large **`metallib-select` Vitest
suite** (bound to baked `METAL_PATH`, byte-identity checks,
deployment-floor parsing, strict vs dev scan behavior) aligned with
**`packages/core/build.ts`** selection logic referenced in CI comments.
> 
> **Decode cache cadence:** flat **`DecodeStep::maintain_cache`** now
calls **`clear_cache` only** (no `synchronize`), with a unit test using
thread-local counters; docs/comments updated across engine and
cache-limit modules.
> 
> **Privacy filter:** **`classify()`** uses
**`maybe_clear_cache_for_privacy_filter_call`** (default every 8 calls,
env override) instead of clearing after every call.
> 
> **Banded attention** takes a caller-supplied **`band_mask`** (build
once per `(T, band)`), rejects negative bands, and **skips bf16/f32
parity tests** when **`test_support`** detects broken half GEMM or
TF32-degraded f32.
> 
> **Quant/convert:** **sym8** extended to **`qwen3_5_moe`** with
co-quant coherence for switch/shared expert trios; **gemma prequant
import** uses **group_size 128**, derives honest top-level
**`quantization` metadata**, and verifies override coverage; related
**convert tests** added.
> 
> **Gemma4** caches **`layer_kinds`** at model init. **LFM2** adds
opt-in **`MLX_LFM2_PAGED_PREFILL_PAGED_ATTENTION`** for graph-native
cache-hit prefill (default off). **Chat session** tests cover multi-MB
image identity hashing.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e2190e3. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Sonnet 5 <[email protected]>
… heal coverage (#84)

## What & why

`cancel_midcycle_then_continue_mtp_matches_ar` was the **only** failure
on main
CI for #83 ([run
28691184880](https://github.com/mlx-node/mlx-node/actions/runs/28691184880),
`e2e qwen3_5-dense`). The
byte-identical PR-head tree (`e2190e36`, tree `6761d493`) **passed** the
same job
on #83's own CI — a flaky oracle, not a product regression. The
RoPE/perf changes
in #83 only shifted the flake odds.

Two root causes, both found by **running** the code rather than
reasoning:

1. **Racy committed count.** The async `handle.cancel()` commits a
host-timing-dependent number of turn-1 tokens (the streaming emit loop
pushes
   each token to `cached_token_history` *before* its cancel check, and a
`"cancelled"` stop — unlike `"length"` — does not force the
trailing-token
drop in `engine/cache.rs`). The old oracle guessed `n_mtp`. Worse, the
committed count isn't observable from the stream:
`ChatStreamChunk.prompt_tokens`
on the streaming delta path is **hardcoded to the delta length** for
both the
warm and the desync-heal arms, and `cached_tokens` is the full prior
history
   either way — neither distinguishes them.

2. **AR is the wrong oracle.** MTP-speculative and plain-AR pick
different tokens
on T=0 argmax near-ties, so an AR reference diverges from the MTP run
regardless
of the heal (a sweep showed byte mismatches at longer budgets even with
matched
   committed length).

## The fix

**Flakiness** — read the real state instead of guessing:
- New read-only `#[doc(hidden)]` hook `mtp_flat_state_for_test() ->
(committed_len,
  flat_mtp_caches_desynced, full_reprefill_count)` (not `#[napi]`).
- `cancel_midcycle_then_continue_mtp_matches_uncancelled` (renamed):
reads the
actual committed history and length-matches an **un-cancelled MTP**
reference's
budget (`b* = n_mtp + (h1_mtp − h1_ref0)`) so both runs commit the
identical
greedy prefix, then asserts the follow-ups are byte-identical. Same
generation
  path on both sides ⇒ equal committed length is an identical prefix.

**Non-vacuous heal coverage** — the cancel test is still vacuous on a
fast host
(the cancel always lands on a clean boundary → turn 2 warm-continues),
so add
`desync_heal_reprefills_to_uncancelled`:
- The flat streaming MTP continue heal is deterministically reachable —
on a flat
(non-paged) model the rebuild gate in
`chat_stream_tokens_delta_sync_inner`
reduces to `flat_mtp_caches_desynced` alone. New
`force_flat_mtp_desync_for_test()`
arms it. The heal re-prefills from `cached_token_history` and discards
the caches,
  so arming the flag on a clean session faithfully exercises it.
- New monotonic `flat_full_reprefill_count` (incremented only in the
streaming-delta
rebuild branch) is the **only** observable proof the rebuild ran. The
test forces
the desync, asserts the counter incremented (heal actually took the
re-prefill
path), and asserts the healed reply equals a byte-identical un-cancelled
MTP
  reference over the same committed history.

## Testing

Verified on M5 (Qwen3.5-0.8B, fresh `mlx convert -m qwen3_5`):

- `cancel_midcycle_then_continue_mtp_matches_uncancelled` — **5/5**
stable
- `desync_heal_reprefills_to_uncancelled` — **5/5** stable
(`healed=true` each run)
- full `qwen3_5_delta_chat` file — **9/9**
- `mlx-core` lib — **1930 passed; 0 failed** (46 ignored)
- `clippy -D warnings` + `cargo fmt --check` clean
- No NAPI surface change (accessors aren't `#[napi]`), so no
`index.d.cts` regen

Two Codex adversarial-review rounds: round 1 `needs-attention` (test
could pass
without exercising the heal) → round 2 **approve** after the
deterministic heal
test + counter.

`model-e2e` label added so the `e2e qwen3_5-dense` job runs the fixed
test on this PR.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Changes are `#[doc(hidden)]` test hooks and e2e test logic only; no
public NAPI surface and no alteration of heal behavior beyond counting
reprefills for observability.
> 
> **Overview**
> Adds **test-only** introspection for flat MTP cache healing: a
monotonic `flat_full_reprefill_count` (incremented when the streaming
delta path discards caches and re-prefills), plus `#[doc(hidden)]`
model-thread commands and async helpers `mtp_flat_state_for_test()` and
`force_flat_mtp_desync_for_test()` to read committed history length,
desync flag, and heal count, or to arm the heal deterministically.
> 
> **`cancel_midcycle_then_continue_mtp_matches_uncancelled`** replaces
the AR oracle with an **un-cancelled MTP** reference whose turn-1 budget
is adjusted from the real `cached_token_history` length (fixing flaky
guesses about cancel vs length stop).
**`desync_heal_reprefills_to_uncancelled`** is new: forces desync,
asserts the reprefill counter increased, and checks turn-2 text matches
a warm MTP run over the same history.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f4c4b21. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
…fc via LinearProj (#85)

## Problem

The qwen3.5 dense `lm_head` and MTP `fc` could only load an **affine**
quantized head. `Linear::load_quantized` / `Linear::forward`
(`crates/mlx-core/src/nn/linear.rs`) hardcode `c"affine"` (dequant +
`mlx_quantized_matmul` mode) and require biases. A micro-scaled head
(nvfp4 / mxfp8 — scales only, no biases) crashed at load:

```
Biases must be provided for affine quantization
```

This is an unfinished early path (commit `08354f84`, PR #32, when affine
was the only mode). It forced NVIDIA-NVFP4 → MLX transcodes to fall back
to an affine-int4 `lm_head` instead of keeping the intended per-layer
bit allocation.

## Fix

Migrate the qwen3.5 dense `lm_head` and both MTP `fc` fields (dense +
moe) from `Linear` / `Option<Linear>` onto the mode-aware `LinearProj`
(`quantized_linear.rs`) and install them via the existing `try_build_ql`
dispatch on `plq.mode` — exactly as **gemma4** and **qwen3_5_moe**
already do for their heads. `Linear::load_quantized` is left untouched
(other families still use it).

```
                       old (affine-only)            new (mode-aware)
lm_head / mtp.fc  ──▶  Linear::load_quantized  ──▶  LinearProj  ─┬─ bf16    → Standard(Linear)
                       (c"affine", needs biases)                 ├─ affine  → Quantized("affine")
                                                                 ├─ mxfp8   → Quantized("mxfp8")   ← was a crash
                                                                 └─ nvfp4   → Quantized("nvfp4")   ← was a crash
```

- **Task 1** `d08372b6` — dense `lm_head: Option<Linear>` →
`Option<LinearProj>`; install in `persistence.rs`; threaded through
every `model.rs` + `paged_forward.rs` forward call site.
- **Task 2** `96e3e450` — MTP `fc: Linear` → `LinearProj` in
`models/qwen3_5/mtp.rs` and `models/qwen3_5_moe/mtp.rs`; removed a stale
"falls through to `set_weight`" comment.
- **Tidy** `293482fb` — two cosmetic follow-ups from the final review
(literal `"affine"` test assertion; `"quantized"` debug label).

No checkpoint or `convert` change — this removes a **loader** constraint
only. Existing checkpoints keep bf16/affine heads unchanged.

## Behavior preservation

- bf16 head/fc → `LinearProj::Standard` → identical
`input.matmul(weight_t)` (heads are bias-free).
- affine head/fc → `LinearProj::Quantized` mode `"affine"` → identical
`mlx_quantized_matmul(x, weight, scales, biases, true, gs, bits,
"affine")` operands.
- tied-embeddings path unchanged (`lm_head` is `None` when tied).

## Validation

3 new install-type unit tests assert the mode dispatch (affine →
`Quantized("affine")`, mxfp8 → `Quantized("mxfp8")`, bf16 → `Standard`)
for the dense head and both MTP fc. `cargo clippy -D warnings` + `cargo
fmt` clean.

E2E runtime (a hand-built qwen3.5-9B checkpoint with an mxfp8 `lm_head`
— scales, no biases):

| Head mode | Result |
|---|---|
| bf16 (0.8b tied, 9B-bf16) | ✅ coherent — unchanged path |
| affine (9B-unsloth) | ✅ coherent — behavior preserved |
| **mxfp8 (9B-mxfp8head)** | ✅ **loads (was a crash) + generates correct
text** — the fix |

> The authoritative GPU parity suite (`qwen3_5_paged_vs_flat_parity`,
`qwen3_5_session`) runs in CI.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches core inference and weight-loading paths for lm_head and MTP
fc; behavior is intended to be parity-preserving for bf16/affine, with
new support for mxfp8/nvfp4.
> 
> **Overview**
> **Fixes quantized checkpoint loading** for dense `lm_head` and MTP
`fc` (dense + MoE): those layers no longer go through affine-only
`Linear::load_quantized`, which failed on mxfp8/nvfp4 heads missing
affine biases.
> 
> They now use **`LinearProj`** with the same **`try_build_ql`** path as
other projections, so affine, mxfp8, mxfp4, and nvfp4 install correctly;
bf16 stays **`LinearProj::Standard`**. **`set_weight`** calls take a
name label (e.g. `"lm_head"`, `"mtp.fc"`). Forward/prefill/paged paths
only change types to **`Option<LinearProj>`**; tied embeddings still
leave **`lm_head`** as **`None`**.
> 
> **Tests** cover install dispatch for dense **`lm_head`** (mxfp8,
affine, bf16, tied) and both MTP **`fc`** modules.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
293482f. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
… draft) (#86)

## Summary

Adds **DSpark speculative decoding** for Gemma 4, using DeepSeek's
[DeepSpec](https://github.com/deepseek-ai/DeepSpec) released draft
checkpoint `deepseek-ai/dspark_gemma4_12b_block7` (external 5-layer
draft transformer for `google/gemma-4-12B-it`).

```
ChatSession (enableMtp auto-on when draft loaded)
  └─ gemma4 dspark_chat_turn
       ├─ chunked prefill w/ hidden taps @ layers [5,17,29,41,46]
       └─ engine run_dspark_turn (per cycle)
            ├─ draft: [anchor, MASK×6] → one non-causal forward
            │         + sequential markov head + confidence truncation
            ├─ verify: ONE target forward over 1+L tokens (w/ taps)
            ├─ accept: greedy argmax / Leviathan rejection sampling
            └─ commit: global KV trim + sliding snapshot/re-append
                       (explicit KV-shared-slot mask, validated every commit)
```

## Usage

```ts
const session = await loadSession('.cache/models/gemma-4-12b-it', {
  draftModelPath: '.cache/models/dspark_gemma4_12b_block7',
});
const res = await session.send('...');   // enableMtp auto-enabled
res.performance.mtpCycles / mtpMeanAcceptedTokensTotal  // acceptance stats
```

## Correctness

Speculative decoding is **lossless at T=0**: the E2E oracle asserts
greedy byte-equality vs plain AR — including generation crossing the
sliding-window (1024) wrap, wrap during prefill, stop shapes (EOS as
boundary AND as accepted draft), warm-continue delta turns, and
streaming==sync.

- Rust `#[ignore]` suite: **6/6 black-box + white-box regressions
green** on the real 12B + draft (`--release --test-threads=1`)
- TS gated e2e green; full `cargo test -p mlx-core` (2000+), `vp test`
(1415), clippy `-D warnings`, fmt, typecheck all clean

## Performance (M5 Max, bf16 12B target)

Mean accepted 2.86–6.05 tokens/cycle depending on content; decode up to
**2.46× AR** (46.8 vs 19.0 tok/s).

## Notable internals

- `RotatingKVCache::snapshot` had a latent aliasing bug (snapshot shared
storage with in-place single-token writes) — fixed and hardened for all
existing users
- Sliding-window rollback: snapshot-before-verify + restore + re-append
of the verify block tail — exact pre- and post-wrap (mlx-lm's trim-based
approach silently breaks post-wrap)
- Draft geometry pinned at load (5L/16H/512/rope/block-7, bf16-only,
mask-token bounds); draft weights materialized at load (cold-mmap
watchdog class); draft's 6.9GB counted in cache-limit accounting
- Cancel/stream residual semantics deliberately match the documented
AR/MTP contract (`engine/decode.rs`), pinned by tests
- Memory: +6.9 GB bf16 draft; docs note the requirement. `mtpDepth` caps
the block (≤7); `mtpAdaptiveDepth` is ignored for gemma4 (confidence
head is DSpark's adaptive mechanism)

Eagle3 (`eagle3_gemma4_12b_ttt7`) can follow as a small PR — it shares
the tap/verify/rollback infra added here.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Large new decode path touching KV commit, sliding-window rollback, and
load-time memory (~7GB draft); incorrect cache or accept logic would
change generation semantics despite T=0 oracles.
> 
> **Overview**
> **Gemma 4** can load an external **DSpark** draft via
`Gemma4Model.load(..., { draftModelPath })` (flat KV only; paged cache
is rejected or forced off). `hasMtpWeights()` exposes draft availability
so **`ChatSession`** can auto-enable the speculative path (`enableMtp`),
reusing existing MTP perf fields for cycle stats.
> 
> The core addition is an **engine-owned propose → verify → accept →
pre-commit stop-clamp → commit** loop (`run_dspark_turn`) behind new
**`DsparkBackend` / `DsparkStepper`** traits, plus a large
**`dspark.rs`** module (checkpoint validation, fused context from tapped
target hiddens, markov + confidence truncation, bf16 loader). Greedy
output is intended to be **lossless at T=0**; a gated TS e2e mirrors the
Rust greedy byte-match oracle.
> 
> **`MxArray.addmm`** is changed to an explicit matmul+scale+add path
instead of fused `addmm`, avoiding a known local metallib miscompile
that dropped bias terms (notably in biased vision linears).
> 
> Docs/README note Gemma4 DSpark; NAPI/types add
**`Gemma4LoadOptions`**. Qwen3.5 config comments are updated for **VLM
default-on block-paged cache** and image-turn behavior (not a full new
feature in this diff slice).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
a656f33. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <[email protected]>
…oints (#88)

## What

Adds gemma-4 **native MTP** speculative decoding: support for Google's
official assistant draft checkpoints
(`google/gemma-4-{12B,26B-A4B,31B}-it-assistant`, apache-2.0, ~800 MB)
as a **second draft variant** next to DSpark (#86), behind the same
`loadSession(path, { draftModelPath })` surface — the loader picks the
variant from the draft checkpoint's `config.json`.

```
DSpark (existing):    5-layer draft, masked block-7 proposals, tapped target hiddens
Assistant MTP (new):  4-layer draft, Q-only attention reading the TARGET's KV caches
                      (last non-KV-shared sliding/full layers), no draft KV, no prefill;
                      one token per step chained through a hidden feedback loop,
                      constant RoPE position per cycle; mtpDepth drafts/cycle (default 3, clamp [1,8])
```

Both variants share the engine turn loop (`run_dspark_turn`),
verify/rollback machinery, stop-clamp semantics, and telemetry. E2B/E4B
assistants (centroid sparse lm_head) are rejected at load with a clear
error — follow-up.

## Design

- `Gemma4Draft { Dspark, Assistant }` enum dispatch (invalid states
unrepresentable); `Gemma4DraftStepper`/`Gemma4DraftTurnState` enums
delegate the engine seam; whole-turn core generalized with exactly 3
variant points.
- Draft reads target K/V **verbatim** (target caches K post-RoPE) via
`get_cached_kv()` re-read after every commit; sliding caches return
temporally-ordered windows.
- Target-side seams: `lm_head_logits` extraction (pure refactor),
`assistant_verify_forward` (logits + post-final-norm hidden),
`assistant_kv_source_indices` (exact `layer_types` matching, consistent
with `should_store_shared_kv`).
- Greedy longest-prefix + Leviathan rejection sampling from the engine —
distribution-preserving at T>0 (stronger than mlx-vlm's naive match).
- **Zero TS surface changes** — proven by the TS e2e passing with no
edits under `packages/` (only doc comments + the server
`extra_body.mtp_depth` cap lift landed there).

## Verification

- **E2E oracles 6/6 green first run** on real 12B
(`tests/gemma4_assistant.rs`): greedy byte-parity vs AR incl.
sliding-window wraps, stop-mid-block + warm delta turn, acceptance
canary, sampled smoke, stream==sync. DSpark regression suite 6/6
unchanged. TS e2e mirror 1/1.
- Unit: 2078 lib tests green; clippy `-D warnings` + fmt clean;
typecheck + type-aware lint clean.
- Per-phase codex adversarial reviews (5 fix rounds all resolved: exact
layer_types KV mapping, draft-dim validation gates ×2, rawText parity
asserts, stale MTP docs + server depth cap) + whole-branch review
**PASS**.

## Numbers (M5 Max, bf16 12B target, greedy, cooled 3 min between runs)

Structured prompt (numbered pancake recipe, 200 tok — same prompt as the
PR #86/#87 quantized benches):

| Path | tok/s | vs AR | accepted/cycle |
|---|---|---|---|
| AR | 18.4 | — | — |
| **Assistant MTP** | **29.9** | **1.63×** | 3.25 |
| DSpark | 27.0 | 1.47× | 3.41 |

Open-prose prompt (pour-over brewing guide, run to EOS ~1.7k tok):

| Path | tok/s | vs AR | accepted/cycle |
|---|---|---|---|
| AR | 19.8 | — | — |
| **Assistant MTP** | **24.5** | **1.24×** | 2.80 |
| DSpark | 27.4 | 1.38× | 3.78 |

Speedup is acceptance-driven and prompt-dependent — the PR #86 "2.46×"
headline was the `decode_wrap` oracle fixture (highly predictable
600-tok continuation, accept 6.05/cycle, the ceiling); its `multi_cycle`
fixture printed 26.7 tok/s accept 3.49, matching these numbers exactly.
The assistant beats DSpark on the structured prompt despite lower
acceptance because its cycles are much cheaper (0.8 GB Q-only draft +
4-row verify at depth 3 vs 6.9 GB draft + 8-row verify at block 7); it
needs no per-cycle context fusion and no draft prefill.

Docs: `docs/models.md` speculative-decoding section covers both
variants; `ChatConfig.mtpDepth`/TSDoc scoped per family.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Large change to the Gemma4 speculative-decode and KV rollback path;
wrong assistant wiring could break greedy parity or session reuse,
though fail-closed reset and T=0 e2e oracles target that.
> 
> **Overview**
> Adds **Google `gemma-4-*-it-assistant`** as a second Gemma4 external
draft alongside DSpark, still loaded through **`loadSession` /
`draftModelPath`** with variant chosen from the draft `config.json`.
> 
> The assistant is a Q-only draft that reads the **target’s committed
KV** (no draft KV / DSpark-style context fusion), chains single-token
proposals with a fixed query position per cycle, and uses
family-specific **`mtpDepth`** (default 3, clamp **[1, 8]**). DSpark and
assistant share a refactored **`Gemma4Draft`** /
**`Gemma4DraftStepper`** / **`draft_chat_turn`** path instead of
DSpark-only `dspark_chat_turn` and `dspark_turn_state`.
> 
> **Server/API:** HTTP mappers stop capping `extra_body.mtp_depth` at 5;
they forward **6–8** and reject invalid values above **64**, leaving
per-family clamps to native code. NAPI/TSDoc now describe both draft
kinds and depth rules.
> 
> **Tests:** New env-gated TS e2e for assistant greedy **byte-parity vs
no-draft** plus real speculative cycles; DSpark e2e also asserts
**`rawText`** parity.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
aff9c98. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <[email protected]>
…fine under --q-mxfp (#89)

## Problem

`apply_mxfp_upgrade` upgraded the four recipe-pinned attention/GDN
projections — `self_attn.o_proj`, `linear_attn.out_proj`,
`linear_attn.in_proj_a`, `linear_attn.in_proj_b` — from **8-bit affine**
to **mxfp8** under `--q-recipe … --q-mxfp`.

The `unsloth`/`qwen3_5` recipes deliberately pin these to 8-bit affine
so AR (M=1) and MTP-verify (M≥2) both route through the M-invariant
`qmv` kernel (T=0 MTP↔AR bit-exactness), and 8-bit **affine**
specifically keeps the worst-KLD `out_proj` (~6.0) near bf16. mxfp8's
coarse E8M0 scales have ~10× the round-trip error of affine 8-bit, so
the upgrade regressed exactly those tensors. The recipe author guarded
against the nvfp4 path but not mxfp, and the CLI help already claimed
"o_proj/out_proj at 8-bit affine" — contradicting the code.

## Fix

- New `is_bitexact_affine_proj` guard in `apply_mxfp_upgrade`, **gated
on the pinned `Custom{bits:8, mode:"affine"}` decision**, so those keys
keep 8-bit affine — symmetric with `apply_nvfp4_upgrade`, mirroring the
existing router-gate / affine-only exclusions. Scoped to
`apply_mxfp_upgrade`; the uniform/no-recipe path is unchanged.
- Decision-scoped (not key-only), so generic `mixed_*` recipes — which
give these keys low bits (e.g. `mixed_4_6` → 4-bit affine `o_proj`) —
still upgrade to mxfp4. `Skip` (MTP layers) is preserved via the main
match.
- Docs/comments made accurate: synced the `quantMxfp` doc across all 6
copies (2 Rust structs + 4 `.d.cts` blocks), fixed the stale `bf16` row
in `cli/README.md`, reworded the `--q-mxfp` help + qualified the run
banner, added `feed_forward.gate` to the router-gate list, and corrected
stale router-gate comments in `convert.rs` / `persistence.rs` /
`sparse_moe.rs` against a verified control-flow trace (decision →
emission → load-time resolution).

## Tests

- New `apply_mxfp_upgrade_preserves_bitexact_affine_projections` (pinned
→ stays affine; MTP `Skip` preserved) and
`apply_mxfp_upgrade_promotes_non_pinned_low_bit_projections` (mixed_*
low-bit → mxfp4).
- 112/112 convert unit tests pass; `yarn typecheck`, `cargo clippy -D
warnings`, `cargo fmt --check` all clean.

## Follow-ups (non-blocking, out of scope of this gap)

- Pre-existing `--q-mode` doc drift: `README.md:133` / `docs/cli.md:83`
say "affine or mxfp8"; the CLI accepts `affine/mxfp4/mxfp8/nvfp4/sym8`
(GGUF: 4 modes) — note the GGUF-vs-SafeTensors mode-support nuance.
- `compute_moe_defaults`' mxfp8 `default_gate_plq` branch is unreachable
for convert-produced checkpoints (now documented) — candidate loader
cleanup.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes quantization decisions for `--q-recipe unsloth|qwen3_5
--q-mxfp` checkpoints (affects model quality and MTP parity); logic is
well-tested but convert output differs from before.
> 
> **Overview**
> Fixes **`--q-mxfp`** incorrectly promoting **`unsloth` / `qwen3_5`**
recipe pins — **`self_attn.o_proj`**, **`linear_attn.out_proj`**,
**`in_proj_a`**, **`in_proj_b`** — from **8-bit affine** to **mxfp8**,
which hurt MTP↔AR bit-exactness and quality on high-KLD layers.
> 
> **`apply_mxfp_upgrade`** now uses **`is_bitexact_affine_proj`**: only
when the inner recipe already returned **`Custom { bits: 8, mode:
"affine" }`** those keys skip the mxfp8 upgrade; **`mixed_*`** low-bit
decisions on the same keys still upgrade to mxfp4. **MoE router gates**
are forced to **8-bit affine** for non-**`Skip`** decisions but
**preserve** an explicit **`Skip`** (aligned with nvfp4).
**`quantMxfp`** docs, CLI **`--q-mxfp`** help, README recipe table, and
MoE gate comments are brought in line with this behavior; two unit tests
cover pinned vs mixed-recipe paths.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
395b8f0. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
…ts) + mlx calibrate (FP8 activations) (#90)

Ports the **whole** NVIDIA modelopt `w4a16_nvfp4-fp8_attn-kv_fp8_cast`
recipe to mlx-node, in two halves that compose: **(A)** the data-free
MXFP4 *weight* quantization at convert time, and **(B)** `mlx
calibrate`, which reproduces modelopt's static FP8 *activation*
quantization (attn/GDN) as Metal fake-quant. Covers both dense `qwen3_5`
and MoE `qwen3_5_moe`.

Validated end-to-end on the real 27B: bf16 `qwen3.6-27b` → `mlx convert
--q-recipe nvidia` (52G→21G, 497 overrides) → `mlx calibrate` (208
attn/GDN `input_amax`, both aliases) → coherent decode; runtime provably
consumes `input_amax` (crushing it to 0.05 degenerates output).

---

## Part A — `mlx convert --q-recipe nvidia` (data-free MXFP4)

A faithful, **data-free** port of the recipe's weight quantization with
**MXFP4 in place of NVFP4**.

**Why data-free:** modelopt's MXFP4 weight quant == MLX's
`mlx_quantize(mode="mxfp4")` (dynamic per-block absmax, E2M1, block 32,
E8M0, **uncalibrated** — modelopt doesn't calibrate weight quantizers).
Calibration only sets FP8 *activation* amax, which Part B handles. No
imatrix, no AWQ prescaling.

| Tensor class | Format |
|---|---|
| FFN gate/up/down (dense `.mlp.*`, MoE `switch_mlp.*`,
`shared_expert.*`) + `lm_head` | mxfp4 4/32 |
| `self_attn.{q,k,v,o}` + GDN
`linear_attn.in_proj_qkv`/`in_proj_z`/`out_proj` | mxfp8 8/32 |
| GDN `in_proj_a`/`in_proj_b` | affine 8/64 |
| router gates (`.mlp.gate`, `.shared_expert_gate`, `.router.proj`,
`.feed_forward.gate`) | affine 8/64 |
| embeddings, norms, conv1d, `A_log`/`dt_bias`, vision, MTP,
`in_proj_ba` | bf16 |

Two conservative deviations from NVIDIA's bf16 (documented in the
builder): a/b → affine 8/64 (T=0 MTP↔AR bit-exactness) and router gates
→ affine 8/64 (mxfp8's coarse E8M0 scales flip top-K). Shared
`validate_nvidia_recipe_options` rejects `--imatrix-path` / `--q-mxfp` /
explicit `--q-bits!=4` / `--q-group-size!=32` on **both** the
SafeTensors and GGUF entry points.

```bash
mlx convert -m qwen3_5     -q --q-recipe nvidia -i <bf16> -o <out>   # dense
mlx convert -m qwen3_5_moe -q --q-recipe nvidia -i <bf16> -o <out>   # MoE
```

## Part B — `mlx calibrate` (native FP8-activation parity)

Makes mlx-node natively reproduce modelopt's static W8A8
FP8-*activation* math for the attn/GDN projections, as Metal
**fake-quant** — numeric parity, not speed (Apple has no FP8 matmul HW).
This is the calibrated half Part A intentionally skipped.

**Graph-level insight** (no new Metal kernel, never touches a quantized
matmul):
```
xq = from_fp8( to_fp8( x · 448/amax ), f32 ) · amax/448     # E4M3 max 448, RNE, saturate; x upcast f32; amax<=0 => passthrough
```
A calibration pass records the running `max|x|` per attn/GDN projection
(modelopt `MaxCalibrator`) and writes `input_amax` into the model
config; the runtime then fake-quants those activations.

```bash
mlx calibrate -i <nvidia-mxfp4-model> --dataset <calib.jsonl> [--calib-size 1024] [--calib-seq 512]
```

**Correctness properties (all test-backed):**
- **Raw-bf16 measurement** — a thread-local flag scopes calibration to
the model thread and *suppresses* fake-quant during the pass, so it
measures raw activations; re-calibration is idempotent (78/78 amax
bit-identical).
- **Non-destructive** — a failed / zero-row / empty-collection run
leaves `config.json` byte-untouched; success writes atomically (temp +
`rename`).
- **Not corruptible** — one guarded public entry
(`calibrateActivationAmaxRaw`); process-wide `try_lock` serialization +
clear-at-start; the arm flag is thread-local so concurrent inference
can't contaminate it.
- **Non-sites untouched** — `input_amax` is consumed only on attn/GDN
activation sites at **both** the writer and loader sides (symmetric
`is_activation_fp8_site` gate); MXFP4 FFN, affine gates, `lm_head`,
`in_proj_ba` are byte-identical to pre-branch, and a non-calibrated
model is unchanged.
- **Token-window fidelity** — full rows go to native;
`encode_sync(add_special_tokens=false)` + `truncate(calib_seq)` is the
only truncation boundary (no tokenizer-blind char slicing).
- **Both families** — `model_type` dispatch routes `qwen3_5` → dense and
`qwen3_5_moe` → MoE `CalibratePrefillRaw`.

## Validation

- Unit tests: convert recipe emits exact per-group `QuantDecision`
(dense + MoE); calibration 18/18 · fp8/E4M3 oracle 30/30 · input_amax +
site-gating 7/7 (incl. non-site drop negatives) · MoE
dispatch/guard/reachability. clippy `-D warnings`, fmt, typecheck clean.
- E2E dense 27B (52G→21G): histogram exactly **193 mxfp4 + 208 mxfp8 +
96 affine = 497**, lm_head mxfp4; calibrate → `0→208 input_amax` (both
aliases, `in_proj_qkvz`→qkv/z fanout); coherent decode that consumes the
amax.
- E2E MoE (agentworld 35B-A3B, 65G→19G): switch_mlp/shared_expert mxfp4,
gates affine; coherent.

Every review finding (8 codex rounds) was verified against real code
before fixing.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Large change to Qwen3.5 quantization, model-thread calibration, and
in-place `config.json` mutation on the inference forward path; mistakes
could skew FP8 scales or corrupt checkpoints.
> 
> **Overview**
> Introduces the **NVIDIA modelopt-style** workflow in two parts: **`mlx
convert --q-recipe nvidia`** applies a fixed per-tensor map (MXFP4
FFN/`lm_head`, MXFP8 attn/GDN, affine gates and GDN a/b) for **`qwen3_5`
/ `qwen3_5_moe`**, with upfront validation (model type from
`config.json`, no imatrix/`--q-mxfp`, pinned bits/group size).
> 
> **`mlx calibrate`** drives native **`calibrateActivationAmaxRaw`**:
raw-text tokenize (no chat template), **token-only** truncation to
`calib_seq`, prefill-only forwards with a thread-local collector on
mxfp8 attn/GDN sites, then **atomic** `input_amax` writes to both
`quantization` aliases (GDN `in_proj_qkvz` fans to split qkv/z). Failed,
empty, or incomplete homing runs leave **`config.json` untouched**.
> 
> Runtime changes thread **`PerLayerQuant::input_amax`** into
**`QuantizedLinear`**: fake-quant activations when calibrated
(suppressed while calibrating), record `max|x|` only on activation-FP8
sites, and drop amax on non-sites like `lm_head`. Adds
**`MxArray::to_fp8`**, process-wide calibration serialization, and
CLI/e2e tests including **no fixed UTF-16 char cap** before native
truncation.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
cc6fcf4. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…#93)

## What

CI's rolling `stable` toolchain bumped to **rustc/clippy 1.97.0
(2026-07-07)**, which added the **"redundant reference in `format!`
argument"** lint. That trips the existing `cargo clippy --all-targets --
-D warnings` gate on a pre-existing line in
`crates/mlx-core/src/tools/mod.rs`:

```rust
error: Some(format!("Tool call missing name: {}", &raw_content)),   // &raw_content is now flagged
```

This is what turned the **Rust Lint → Clippy** job red on `main` (first
failure on #89, then the #90 merge — run `29022183758`). The code itself
dates back to #64; nothing on #90 touched it — a toolchain bump surfaced
it.

## Fix

Inline the captured identifier:

```rust
error: Some(format!("Tool call missing name: {raw_content}")),
```

`raw_content` is still moved into the struct field on the next line, so
behavior is unchanged.

## Verification

Reproduced the CI toolchain locally (`rustup update stable` → clippy
`0.1.97 (2d8144b788 2026-07-07)`) and ran the exact gate:

```
cargo clippy -p mlx-core --all-targets -- -D warnings
    Finished `dev` profile in 2m 34s   # exit 0, no redundant-reference error
```

Only remaining output is the pre-existing `block v0.1.6` future-incompat
note (present on all green runs; not a `-D warnings` failure).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> One-line formatting change in an error message path; no logic or API
changes.
> 
> **Overview**
> Unblocks **Rust Lint → Clippy** on CI after **clippy 0.1.97** started
enforcing the redundant-reference-in-`format!` lint under `-D warnings`.
> 
> In `ToolCallResult::missing_name`, the error string now uses inline
capture (`{raw_content}`) instead of `{}", &raw_content`. The message
and move semantics are unchanged.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
44cc4cd. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
…) + fail-closed fixes (#94)

## Summary

vLLM-aligned per-turn execution planning: a new `engine/plan.rs`
(`TurnPlan`/`ExecutionPlan`) replaces scattered per-family probes so
paged/flat/speculative routing and delta-turn admission are decided in
one typed place, plus a model-loader registry rework in `@mlx-node/lm`
and a new `docs/inference-architecture.md`. On top of the refactor
baseline, three fixes close every blocker found in review:

- **Model loader fails closed** — malformed `config.json` (non-object
root, numeric/object `architectures`) now throws
`MalformedModelConfigError` instead of silently loading as qwen3;
`LoadableModel` is restored to the native `@mlx-node/core` class union
(registry rows carry `nativeModelClass`), so downstream native-instance
assignments keep compiling.
- **Gemma4 media prepare fails closed** —
`media_session_context`/`paged_text_turn_context` are cleared only after
the fallible paged prepare succeeds, and the text-delta guards consult
`session_media()`; a block-exhaustion failure now yields the typed
`IMAGE_CHANGE_REQUIRES_SESSION_RESTART:` rejection in both windows (keys
set, and warm-continued sessions where provenance lives only in the
context).
- **LFM2 delta turns stay paged** — `supports_delta: true`;
continuations ride the single existing `run_paged_turn` warm
strict-extension path (adapter block reuse + conv Pass-1
reconstruction). This ends the reproduced corruption where a paged fresh
turn + flat delta tail-prefilled onto never-populated flat attention KV
and emitted input-independent repeated `<think>` tokens. The parity
suite gains a content-sensitive memory-probe oracle (the old one passed
on a 48-token context-insensitive prompt).

## Verification

- Per-fix: TDD where applicable, `cargo clippy --all-targets -- -D
warnings`, `cargo fmt --check`, `yarn typecheck`, `vp lint --type-aware
--type-check`, full `cargo test -p mlx-core` green.
- LFM2 E2E on the real 1.2B checkpoint: parity suite 8/8; 3-turn TS
session (paged default) cachedTokens 0→494→683 with correct recall
answers matching the forced-flat control.
- Each fix passed a task-scoped adversarial review; the final
whole-branch adversarial review returned PASS with zero findings.

## Follow-ups (triaged, not blockers)

- Gemma4 media cores record `first_token_instant` after the decode loop
(invalid media TTFT/decode telemetry; pre-existing from #70).
- Silent MTP→AR fallback on paged checkpoints (`mtpCycles: 0` with
`enableMtp: true`) deserves an explicit signal.
- Dense/MoE plan-helper duplication (qwen3_5 ↔ qwen3_5_moe), gemma4
`paged_text_turn_context` side-channel → explicit save-context
parameter, registry-derived draft-model error message.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Changes core chat routing, speculative/media session semantics, and
model detection fail-closed behavior across many families; incorrect
planning or Gemma4 media state would corrupt KV reuse or mis-load
checkpoints.
> 
> **Overview**
> Introduces **`engine/plan.rs`** so each chat turn is planned once from
load-time **`ExecutionPlan`** and request facts (**`TurnPlan`**: media
input vs live context, paged attention, speculative decoder,
**`TurnPath`**). The session core stops chaining **`has_paged_adapter` /
`vision_turn` / `mtp_turn` probes** and instead calls required
**`run_paged_turn`**, **`run_speculative_turn`**, or
**`run_multimodal_turn`** handlers with bundled **`MediaInputs`** and
**`text_delta_media_guard`**.
> 
> **Gemma4** advertises media via **`gemma4_media_plan`** (truthful
encoders vs backend-validated admission), tracks persistent
**`media_session_context`**, and only clears media provenance after a
successful paged prepare so failed prepares still fail closed through
**`session_media()`**. **LFM2** sets **`supports_delta: true`** so
session continuations stay on the generic paged path instead of flat
tail-prefill on empty attention KV.
> 
> The **@mlx-node/lm** loader gains broad registry/detection tests
(architecture precedence, malformed **`config.json`** errors,
**`LoadableModel`** compile-time probes);
**`docs/inference-architecture.md`** is linked from **`CLAUDE.md`**.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8c0f052. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <[email protected]>
## `mlx agent` — mlx-node's first all-in-one local coding agent

One command, a local model, local tools, **no API keys and no cloud
hop**. `mlx agent` embeds the [pi](https://github.com/earendil-works/pi)
coding-agent SDK (MIT, `@earendil-works/*@0.80.6`) and drives it against
an **in-process `@mlx-node/lm` ChatSession** — inference runs in the
same process, so there is no HTTP server and no localhost port.

```
┌─ mlx agent ────────────────────────────┐
│  packages/agent (@mlx-node/agent)       │
│  ┌───────────────────────────────────┐  │
│  │ pi-coding-agent SDK (full compose)│  │  TUI · sessions · compaction ·
│  │                                   │  │  extensions · skills · themes ·
│  └───────────────┬───────────────────┘  │  slash cmds · /model · AGENTS.md
│         mlx provider bridge             │
│  ┌───────────────▼───────────────────┐  │
│  │ ChatSession (@mlx-node/lm)         │  │  in-process — no HTTP, no keys
│  └───────────────────────────────────┘  │
└─────────────────────────────────────────┘
```

### What you get
- `mlx agent` boots the full pi surface — TUI, JSONL session trees
(`-c`/`--resume`/fork), `/compact` auto-compaction, `/model` picker,
extensions/skills/prompts/themes, AGENTS.md/CLAUDE.md context loading,
print (`-p`) and RPC modes — all pointed at a local model.
- **In-process provider bridge** via `pi.registerProvider("mlx", …)` so
mlx models are first-class at every LLM call site (main loop,
compaction, branch summaries). Each turn cold-replays through
`primeHistory` + `startFromHistoryStream` with native KV-prefix reuse,
so it stays warm while sidestepping ChatSession's
one-unresolved-tool-call limit.
- **Permission gate** (pi ships none) — Yes / Always-this-session / No
prompts for `bash`/`write`/`edit`, discloses pi's effective
`shellCommandPrefix`, encodes (never deletes) shell-significant/control
bytes in the prompt, fails closed, and blocks in non-interactive mode
unless `MLX_AGENT_AUTO_APPROVE=1`.
- **First-run wizard** — empty models dir → interactive catalog picker →
downloads via existing `mlx download` machinery → starts. Config home is
`~/.mlx-node/agent/*`.
- **`--q-recipe nvidia` extended to dense gemma4** — mxfp4 MLP + mxfp8
attention, tied head + vision bf16; produced the validated Gemma-4-12B
build the catalog points at.

### Structure
New `packages/agent` (`@mlx-node/agent`): provider bridge
(`stream-adapter`, `convert-messages`, `chat-config`, `events`,
`model-host`, `models`, ported `tool-call-buffer` + `warm-reuse`),
`permission-gate` extension, curated `catalog`, `run-agent` shell. Wired
into `packages/cli` (`mlx agent` command + wizard) and
`crates/mlx-core/src/convert.rs` (nvidia recipe for gemma4). Docs:
`docs/cli.md` `## mlx agent` + README.

### How it was built & verified
Executed via subagent-driven development — 10 tasks, each gated by an
adversarial codex review, then a **holistic whole-branch review**. That
final pass surfaced 5 cross-cutting interaction defects the per-task
reviews structurally couldn't (non-string `shellCommandPrefix`
under-disclosure, a gemma4_unified QAT reaching the audio-dropping E2B
importer, a settings-seed clobber of malformed `settings.json`, partial
error/aborted turns replayed into a reset session, and an arg-scan value
hijack) — all fixed and re-reviewed to **VERDICT: PASS, zero findings**.

Gates (all green): `yarn typecheck`, TS suites 146/146, `cargo test -p
mlx-core --lib` (nvidia_recipe 18/0, gemma 321/0, + hermetic unified-QAT
reject), `vp lint --type-aware`, `cargo clippy -D warnings`, `cargo fmt
--check`. Model-heavy provider/E2E tests are gated behind
`describe.skipIf` and skip cleanly in CI.

### Follow-up (non-blocking)
The **Gemma-4-12B** catalog slot is present but **hidden** pending the
maintainer uploading the validated `Gemma-4-12B-IT-nvidia-mxfp-mlx` (8.6
GB) build to Hugging Face. Once the repo slug is final: un-hide the
entry in `packages/agent/src/catalog.ts` and drop the wizard
hidden-guard test block. The agent ships fully functional with the other
catalog models in the meantime.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> New permission-gated tool execution and argv/settings handling affect
local-first routing and user data paths; conversion recipe changes touch
quantization for gemma4 dense builds but are gated with explicit rejects
for MoE and gemma-QAT misuse.
> 
> **Overview**
> Adds **`mlx agent`**, an offline coding agent that embeds the **pi**
SDK (`@earendil-works/*@0.80.6`) and routes every LLM turn through an
**in-process `@mlx-node/lm` `ChatSession`** (no HTTP server or API
keys).
> 
> The new **`@mlx-node/agent`** package registers an **mlx provider
bridge** (message conversion, streaming adapter, warm KV reuse via
history replay), a **permission gate** for `bash`/`write`/`edit`
(interactive approve or `MLX_AGENT_AUTO_APPROVE=1`), model
discovery/hosting, and a **curated download catalog**.
**`packages/cli`** wires **`scanAgentArgs` / `withDefaultModel` /
`run()`** so pi flags pass through, local models are injected ahead of
cloud defaults, session/provider runs get **`--models mlx/*`**, settings
under **`~/.mlx-node/agent`** are seeded write-once, and **`update`** is
blocked.
> 
> **First-run wizard** downloads a visible catalog entry via existing
**`mlx download`** when no local checkpoint exists. **`--q-recipe
nvidia`** validation and the recipe map are extended to **dense `gemma4`
/ `gemma4_unified`** (mxfp4 MLP, mxfp8 attention; MoE gemma4 rejected),
supporting the validated Gemma-4-12B build (catalog entry present but
**hidden** until HF publish). README and **`docs/cli.md`** document the
command.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5374d69. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <[email protected]>
….6 (#96)

## Summary

- add the official Unsloth float-class maps for verified Qwen3.5/Qwen3.6
hybrid checkpoints
- translate the Apple path from NVFP4/FP8 to MXFP4/MXFP8 while retaining
NVFP4 for the DGX path
- share the family/shape-gated selector across SafeTensors and GGUF
conversion
- preserve legacy Dynamic 2.0 behavior for plain affine and
non-Qwen/ambiguous inputs
- document both commands and report pre-conversion selection as pending
backend family/shape verification

## Recipe maps

- `--q-recipe unsloth --q-mxfp`: early FFNs use MXFP4 4/32
- `--q-recipe unsloth --q-mode nvfp4`: early FFNs use NVFP4 4/16
- both: final eight FFNs, attention q/k/v/o, GDN qkv/z/out, and
`lm_head` use MXFP8 8/32
- both: embeddings, routers, GDN a/b, vision, MTP, norms, and recurrent
parameters remain BF16
- AWQ imatrix pre-scaling is unchanged

This follows the [official Unsloth Qwen3.6 NVFP4 class
map](https://unsloth.ai/docs/models/qwen3.6#nvfp4), substituting
MXFP4/MXFP8 only for the Apple-oriented path.

## Root cause

The previous `--q-mxfp` path mechanically upgraded legacy Dynamic 2.0
affine decisions, leaving several sensitive classes as 5/6/8-bit affine
instead of applying the official float-class map. The existing DGX path
similarly promoted only legacy 4-bit decisions to NVFP4. Both entry
points also needed an explicit Qwen family-and-shape gate so
Qwen-specific MXFP heads could not be emitted for incompatible model
families.

## Validation

- `cargo test -p mlx-core --lib convert::tests` — 141 passed, 1 ignored
- GGUF recipe tests — 8 passed
- CLI conversion tests — 14 passed
- `cargo clippy -p mlx-core --lib -- -D warnings`
- `cargo fmt --check`
- `git diff --check`

Local generated artifacts (not committed):

- Qwen3.5 35B-A3B MoE MXFP: 192 MXFP4 + 179 MXFP8 tensors; load and
one-token smoke passed
- Qwen3.6 27B NVIDIA: 193 MXFP4 + 208 MXFP8 + 96 affine8 tensors; load
and one-token smoke passed
- Qwen3.6 27B DGX: 168 NVFP4 + 233 MXFP8 tensors; load and one-token
smoke passed

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes quantization outputs for Unsloth + `--q-mxfp`/`nvfp4` on Qwen
hybrids; gating limits blast radius, but wrong gate logic could
mis-quantize or leave sensitive layers in unexpected formats.
> 
> **Overview**
> Adds **official Unsloth float-class quantization** for verified
Qwen3.5/Qwen3.6 hybrid checkpoints when using `--q-recipe unsloth` with
either `--q-mxfp` (early FFNs → MXFP4, high classes → MXFP8) or
`--q-mode nvfp4` (early FFNs → NVFP4 4/16, same MXFP8/BF16 split). This
replaces the prior path that only **mechanically upgraded** legacy
Dynamic 2.0 affine decisions.
> 
> **Gating:** Activation requires matching config family, requested
model type, and hybrid tensor shape (full attention + GDN keys).
Non-Qwen, mismatched, or plain affine Unsloth inputs still use Dynamic
2.0 plus `apply_mxfp_upgrade` / `apply_nvfp4_upgrade`.
> 
> **Scope:** The new predicate covers layer-depth rules (final eight
FFNs MXFP8), MoE/shared experts, `lm_head` MXFP8, and BF16 exclusions
(embeddings, routers, GDN a/b, vision, MTP). The same selector is wired
in **SafeTensors** (`convert.rs`) and **GGUF**
(`is_qwen35_hybrid_gguf`).
> 
> **CLI/docs:** Help and convert logs describe the official maps as
**requested** until the backend verifies family/shape; tests cover
messaging and flag forwarding.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
5d75264. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary

- run Pi subagents as isolated in-process sessions that share one
serialized `MlxModelHost`, model registry, and physical paged KV pool
instead of loading one model per child process
- size Qwen3.5/Qwen3.6 dense and MoE paged pools after weight
materialization from live unified-memory ceilings; explicit cache
budgets remain maxima and cannot bypass the safety cap
- publish the physical context window to Pi, scale subagent compaction
budgets, preflight exact rendered prompts, and convert capacity failures
into clean agent compaction or HTTP 400 paths
- force a full-history replay after interrupted or failed native deltas
so JavaScript history cannot diverge from committed native cache state
- add a restart-safe SSD cold-cache primitive with stable model/prefix
keys, checksummed safetensors, bounded atomic writes, quota/LRU
enforcement, and transactional restore
- preserve the earlier terminal-title, split reasoning-tag, and
permission-summary fixes in this branch
- request native timing metrics and show transient prefill/decode tok/s
in Pi's TUI footer; clear stale rates at turn/model boundaries without
persisting telemetry

## Why the allocator exhausted

The previous fixed/default pool could advertise a 262,144-token trained
window while physically holding about 104,848 tokens. Pi therefore
continued sending turns after the hot KV pool was full, producing
`BlockAllocator exhausted`. The loaded model now exposes both trained
and physical limits, and both TypeScript and native paged entry points
reject or clamp before allocator mutation.

## Shared-host behavior

Parallel subagents may run up to four independent Pi tool loops, but all
inference is serialized through one resident model host. Each subagent
keeps independent in-memory conversation, settings, cwd, tools, skills,
and project context. Model weights and the paged pool are loaded only
once for the shared model.

## SSD tier boundary

This PR provides and verifies the durable cold-cache storage/restore
layer, but does not enable Qwen eviction yet. Qwen3.5/3.6 hybrid
continuation also needs matching GDN and MTP side state; restoring
full-attention K/V alone would be incorrect. Wiring eviction is
intentionally deferred until that sidecar can be captured and restored
atomically.

Top-level Pi still needs an upstream `SettingsManager` injection/update
hook to scale its fixed compaction reserve for unusually small physical
windows. In-process subagents are scaled here; exact preflight remains
the correctness backstop everywhere.

## Verification

- full TypeScript suite: 1,737 passed, 21 skipped
- focused agent/session/server integration: 485 passed
- agent provider/TUI telemetry suite: 221 passed
- paged-attention Rust suite: 118 passed
- native capacity boundary tests: 3 passed
- `cargo check -p mlx-core`
- clippy for `mlx-core` and `mlx-paged-attn` with warnings denied
- TypeScript typecheck and lint
- Rust and TypeScript formatting checks
- full release native addon rebuild

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Changes span serialized multi-agent inference, physical KV/context
limits, native cache replay semantics, and paged-attention override
cloning—errors can cause wrong model routing, context corruption, or
allocator failures under load.
> 
> **Overview**
> **Agent CLI and Pi handoff** now strips `--trace` / `--trace-dir`,
configures `MLX_NODE_LOG` / `MLX_NODE_LOG_FILE` before the native addon
loads, and prepends `--models mlx/*` on most runs so Pi cannot pick a
cloud default while still restoring fork/session models. **Context
capacity** is checked in `ChatSession` (including image-expanded
prompts) and in HTTP streaming handlers so oversize requests return JSON
`context_length_exceeded` before SSE or native cache mutation; output
`maxNewTokens` is clamped to the physical window.
> 
> **Session recovery** resets native caches and **cold-replays preserved
history** after failed or abandoned delta/tool/stream paths instead of
issuing another delta on possibly desynced KV state. **Paged config
overrides** move behind `PagedConfigOverrideManager` with separate
launch-claude vs agent policies (Gemma draft hiding, MTP sidecar
symlinks, collision-safe roots, cleanup races).
> 
> **Native (`mlx-core`)** adds optional `cache_owner_id` /
`cache_root_owner_id` on `ChatConfig`, structured MLX eval errors and
`deep_copy`, decode-profiler token/TTFT accounting fixes, VLM
paged-prefix downgrade when GDN sidecars are missing, image-aware
cache-key helpers, and DSpark adaptive AR-fallback hooks. **Gemma4** e2e
expectations shift: pure images warm-continue; audio cold-replays with
`cachedTokens === 0`. **`image`** crate enables **GIF** decoding.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
eba950d. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

<!-- PERF_UPDATE_START -->
## Qwen3.5 / Qwen3.6 dense and MoE performance update

- keep PagedAttention enabled and use an exact-shape grouped-GQA Metal
path for BF16 `D256/BS16` long-context decode: dense `24Q/4KV` and MoE
`16Q/2KV`, including two-row MTP verification
- preserve generic V2 below measured crossover points, on unsupported
devices, and for every other shape; capability or pipeline failures fall
back instead of failing inference
- use conservative layout-specific cutoffs: dense 16K q1 / 8K q2, MoE
32K q1 / 16K q2
- align graph-native C++ and raw Rust dispatch, stripe/reducer
scheduling, auxiliary-memory estimates, cache accounting, and permanent
numerical-parity coverage
- capture materialized MoE GDN state at the final reusable paged-block
boundary, restore it by exact token/hash/namespace match before suffix
prefill, and bound/materialize full-prefix replay on a miss
- fix AR/MTP profiling so prefill, TTFT, generated-token count, N-1
decode throughput, replay errors, and TUI metric persistence describe
the same turn
- use normal configurable tracing for inference diagnostics
- replace deprecated `metal-rs 0.33` / `objc 0.2` / `block 0.1.6` with a
narrow ownership-aware adapter over `objc2 0.6.4` and `objc2-metal
0.3.2`

### Measurements

Controlled 16K / 128-token runs on the local Qwen3.6-27B MXFP4+MXFP8
dense model, with one loaded model and cold cache before each trial:

| Trial | Prefill | Decode |
| --- | ---: | ---: |
| AR 1 | 686.9 tok/s | 20.6 tok/s |
| MTP depth 1 | 577.2 tok/s | 18.1 tok/s |
| AR 2 | 540.7 tok/s | 19.1 tok/s |

The bracketing AR weighted decode rate was 19.8 tok/s; MTP reached 91.4%
of it with a mean commit of 1.826 tokens/cycle. This confirms the
profiler fix and rules out the earlier 12 tok/s report as the healthy
short-context baseline.

For Qwen3.6-35B-A3B without MTP, the pre-fix mlx-agent trace reached
about 584 tok/s prefill but only 24.2 tok/s decode near 91K context. The
corrected oMLX comparison supplied for the same M5 Max class is 547.3
tok/s prefill and 44.9 tok/s decode at 128K, so prefill is already in
range and long-context decode is the remaining gap.

Isolated `16Q/2KV` raw-attention A/B at 112K cached tokens improved q1
from 3.770 ms to 1.441 ms and q2 from 4.294 ms to 2.148 ms. The release
addon is rebuilt; full-model post-fix 35B-A3B validation is pending the
next mlx-agent trace.

### Additional verification

- grouped graph numerical parity covers dense/MoE and q1/q2
- raw Metal host-reference parity covers dense 24Q/4KV and MoE 16Q/2KV
q1/q2, including non-finite rejection
- layout-specific selector, threshold, capability, and auxiliary-sizing
tests
- MoE GDN forced-boundary split parity, exact publish/restore,
token/salt rejection, and bounded-replay state parity
- profiler accounting: 26 passed
- MTP turn control flow: 23 passed
- agent CLI/tracing/TUI tests: 84 passed
- strict Clippy for `mlx-core`, `mlx-paged-attn`, and `mlx-metal`
- TypeScript build, Rust format, diff check, lint, and release native
addon/metallib rebuild
- dependency-tree proof: `block 0.1.6`, `objc 0.2.7`, and `metal 0.33`
are absent
<!-- PERF_UPDATE_END -->

<!-- GEMMA4_UPDATE_START -->
## Gemma4 QAT conversion and agent inference update

- preserve source GGUF Q4_0/Q4_1/Q8_0 block-32 affine geometry in MLX
safetensors; dequantize the supported Gemma4 Q6_K token embedding to
BF16, and reject unsupported Q6_K placements
- add `--config-dir` plus Gemma4 mmproj remapping so authoritative
config/tokenizer assets and unified vision/audio tensors can be carried
into the converted checkpoint
- load unified media sidecars only when the parsed Gemma4 capabilities
require them, and hoist BF16 affine-QMM FP16 sidecar widening to model
load while preserving projection outputs
- preserve the thinking-mode provenance used to render historical
assistant turns so prompt-cache replay remains byte-stable
- auto-discover an embedded Gemma4 `draft/`; `mlx agent` continues to
prefer paged AR and requires `MLX_AGENT_ENABLE_GEMMA_DRAFT=1` for the
flat speculative path
- add a measured per-turn DSpark break-even guard that falls back to
exact target AR when speculation loses, while explicit depth/adaptive
settings retain their documented control
- add Gemma4 cache-hit prefill/sliding-checkpoint plumbing and an
experimental BF16 D512/16Q/1KV grouped paged-attention kernel with
graph/reducer parity coverage

The grouped Gemma4 D512 route remains default-off and diagnostic until
sequential full-model A/B establishes a safe context/device crossover.
The latest 47K-context agent trace confirmed prompt-cache and physical
paging correctness at 607.7 tok/s bulk prefill and 15.3 tok/s decode;
this update does not claim that the default long-context decode gap is
closed yet.

The final unresolved review thread is also addressed: paged override
clones now preserve only loader-known Qwen3.5 nested MTP sidecars and
reject escaping paths while keeping unrelated directories and Gemma4
`draft/` hidden.

### Additional verification

- Qwen paged-override regression suite: 20/20
- TypeScript typecheck and focused lint
- Rust and changed-file TypeScript formatting
- `git diff --check`
- full native/Metal validation delegated to the fresh GitHub CI run
because a user `mlx agent` session is active locally
<!-- GEMMA4_UPDATE_END -->
## Summary

- show TTFT and per-turn input/cache context alongside prefill and
decode throughput
- distinguish tiny warm-cache suffixes from comparable bulk-prefill
measurements
- preserve the original rate-only footer when optional context metadata
is malformed

## Root cause

The agent footer retained only the native prefill and decode rates. On a
warm Qwen session, prefill throughput is measured over the fresh suffix
while TTFT also includes cache restoration and long-context first-token
work. A small suffix such as 42 new tokens over a 114.6K-token cached
prefix could therefore display `74.8 tok/s` with no indication that it
was not a bulk-prefill benchmark.

The completed Pi message already contains the fresh input and cache-read
counts, so this change adds that existing context without changing
native metrics or public schemas.

Example:

```text
mlx · TTFT 561.7 ms · input 42 new + 114.6k cached · prefill 74.8 tok/s · decode 42.5 tok/s
```

## Validation

- `yarn vp test packages/agent/__test__/performance-status.test.ts
packages/agent/__test__/stream-adapter.test.ts
packages/agent/__test__/events.test.ts` (69 passed)
- `yarn exec tsc -b packages/agent/tsconfig.json --pretty false`
- `yarn vp lint packages/agent/src/provider/performance-status.ts
packages/agent/__test__/performance-status.test.ts
packages/agent/__test__/stream-adapter.test.ts`
- `yarn vp fmt --check packages/agent/src/provider/performance-status.ts
packages/agent/__test__/performance-status.test.ts
packages/agent/__test__/stream-adapter.test.ts`

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Display-only TUI status formatting with defensive validation; no auth,
persistence, or inference behavior changes beyond what is shown in the
footer.
> 
> **Overview**
> The agent TUI **mlx performance footer** now adds **TTFT** and
**per-turn input context** (fresh vs cached tokens) next to the existing
prefill/decode throughput, so warm-cache turns do not look like
bulk-prefill benchmarks when only a small suffix was prefilled.
> 
> `PerformanceStatus.record` pulls optional **TTFT** from native metrics
and **input/cacheRead** from the completed assistant message’s usage;
formatting distinguishes **“N new + M cached”** when `cacheRead > 0`,
otherwise a single input count. If TTFT or usage counts are invalid, the
footer **falls back** to the previous rate-only line.
> 
> Tests cover tiny vs bulk cached suffixes, malformed metadata fallback,
and assert the stream adapter still attaches **usage** (`input` /
`cacheRead`) on the Pi assistant message used for recording.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
c851da8. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
## Summary

- allow the verified official Qwen3.5/Qwen3.6 MXFP4/MXFP8 and
NVFP4/MXFP8 class maps to run without an imatrix
- keep legacy affine Unsloth fail-closed and require `--imatrix-path`
- verify the model family and sanitized hybrid tensor shape before
allowing a no-imatrix request, in both SafeTensors and direct GGUF
conversion paths
- warn that AWQ pre-scaling is skipped and quantization quality may be
lower while preserving the fixed class map
- update CLI help, documentation, and regression coverage

## Why

The fixed Unsloth class maps are deterministic, but the converter
previously rejected every Unsloth invocation without an imatrix. That
blocked compatible checkpoints which do not publish calibration data.
Simply removing the early check would be unsafe because unsupported or
ambiguous inputs could silently fall back to the legacy Dynamic 2.0
predicate without AWQ calibration.

This change only defers the imatrix requirement for `--q-mxfp` and
`--q-mode nvfp4`, then requires the backend's existing Qwen family and
hybrid-shape verification to select an official map. All other
no-imatrix Unsloth requests still fail.

## Validation

- `yarn vp test packages/cli/__test__/convert-cmd.test.ts --run` — 19
passed
- `cargo test -p mlx-core unsloth_no_imatrix --lib` — 3 passed
- `yarn typecheck`
- `cargo fmt --all -- --check`
- `git diff --check`
- converted Ornith-1.0-35B through both no-imatrix paths:
  - MXFP variant: 192 MXFP4 + 179 MXFP8 tensors
  - DGX variant: 192 NVFP4 + 179 MXFP8 tensors
- both outputs: 1,437 indexed tensors, 371 scales, zero affine biases,
five shards

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes quantization validation and conversion entry points across
Rust and CLI; incorrect gating could reject valid converts or allow
low-quality legacy Unsloth without calibration, but scope is limited to
convert tooling rather than runtime inference or auth.
> 
> **Overview**
> **Unsloth without calibration** is now allowed only for the verified
official Qwen3.5/Qwen3.6 fixed class maps (`--q-mxfp` or `--q-mode
nvfp4`). Legacy affine `--q-recipe unsloth` still **requires**
`--imatrix-path`.
> 
> The converter adds **early** and **late** imatrix gates in
`convert.rs` (shared by SafeTensors and GGUF): defer fixed-map requests
at the CLI, then **fail closed** if family/shape verification does not
select an official map—so callers cannot silently fall back to legacy
Dynamic 2.0 without AWQ. Official-map selection runs **before**
model-specific branches (e.g. privacy-filter) so dedicated predicates
cannot skip that check. A warning is emitted when AWQ pre-scaling is
skipped.
> 
> **CLI and docs** mirror the policy: optional imatrix for fixed maps,
warnings on no-imatrix runs, and tests for legacy rejection vs allowed
MXFP/NVFP paths. **`mlx convert`** rejects `--quantize` on foreign types
`pp-lcnet-ori` and `uvdoc` before backend conversion.
> 
> The **GRPO optimizer round-trip test** is rewritten to seed a
deterministic AdamW SafeTensors fixture and exercise load → save → load
→ save on the model thread, replacing flaky GRPO training/retry logic.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
ec4d953. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
…e NAX tensor op, and running Google's QAT GGUF (#101)

Loads, converts and runs llama.cpp / Unsloth-Dynamic GGUFs whose tensors
are ggml K-quants (Q6_K, Q4_K, Q5_K) with weights **bit-identical to
llama.cpp's**, at ggml byte size, on native Metal kernels — rather than
requantizing into MLX's affine format, which is lossy and, where it is
exact, *larger* than the source (Q6_K → affine needs `group_size=16`,
costing an fp16 scale **and** bias per 16 weights = 8.0 bpw against
ggml's 6.5625).

Concretely, this is what makes Google's QAT checkpoint usable:
`gemma-4-12b-it-qat-q4_0-gguf` is published **GGUF-only**, and
quantization-aware training is exactly the case where requantizing
throws away the thing you wanted. It now converts 1:1 and generates.

## The idea

K-quants are algebraically affine per sub-block:

```
Q4_K/Q5_K   y = d·sc[j]·q − dmin·m[j]   →  scale = d·sc[j]   bias = −dmin·m[j]
Q6_K        y = d·sc[j]·(q−32)          →  scale = d·sc[j]   bias = −32·d·sc[j]
```

So a K-quant kernel is MLX's **affine** kernel with the scalar `(scale,
bias)` load replaced by a two-level decode. `qdot`, `qdot_safe`,
`qouter`, `dequantize` and `load_vector` needed **zero change**. Codes
are repacked at import into MLX's LSB-first bitstream, which dissolves
two blockers: ggml's 210-byte block stride cannot be a `uint32` array
(210 = 2·3·5·7) and faults MLX's vectorized loads, and scales living
*inside* the weight block are inexpressible in the kernel ABI.

Sub-scales ride in the existing `.scales`/`.biases` sidecars as
interleaved pairs, so FFI arity stays at 2 companion arrays and no new
symbols were needed. `.biases` holds ggml's `d`, which is a **scale, not
an additive bias** — documented at every producer and consumer.

## Evidence

**Import is bit-exact against llama.cpp's own decoder.** The reference
is not a transliteration: it is `llama-quantize … F32` output, i.e.
ggml's `dequantize_row_q{4,5,6}_K`. Per format, 198 tensors and
751,566,848 elements (re-run at this tip on freshly built fixtures —
full table under *Verification*):

| format | bit-identical | unexplained diffs |
|---|---|---|
| q4k | 751,566,848 / 751,566,848 | 0 |
| q5k | 751,566,848 / 751,566,848 | 0 |
| q6k | 741,668,535 | 0 — remainder is signed-zero reassociation, both
sides asserted zero |
| Q8_0 (affine control) | 140,014,524 | 0 — differs only by f16 rounding
of the scale·code+bias product, asserted rather than tolerated |

**And bit-exact against the real checkpoint it exists for.**
Independently of the pure-format fixtures, the converted Google QAT
model was compared byte for byte against the GGUF it came from — all 328
Q4_0 tensors and every one of the Q6_K embedding's 3,932,160
super-blocks, 0 mismatches, size accounting residual 0. Details in
*Running Google's QAT checkpoint*.

**The Metal kernels are correct, proven by kernel identity rather than
by a tolerance passing.** Same binary, only `MLX_ENABLE_TF32` differing:
on → the smallest K-quant float32 `qmm_t` gap is 2.276e-4 (q6k),
3.194e-4 (q4k), 3.348e-4 (q5k); off → exactly `0.000e0`. Two results
from identical inputs means two different kernels. The residual is
tf32's 10-bit mantissa, not a decode error — the *affine* control, with
no K-quant code in its path, measures 4.280e-4, **wider** than any
K-quant.

**Prefill was 3.4× slower before the NAX kernels, and is now level with
affine.** `M=512 N=8192 K=8192`, bfloat16, 12 reps × 9 rounds, cooled:

```
config              ms       TFLOP/s   vs affine_A
affine_A (control)  1.6474    41.71      1.0000
affine_B (control)  1.6387    41.94      0.9947 ± 0.0130   ← A/A control
q6k                 1.7404    39.49      1.0564 ± 0.0226
q4k                 1.5894    43.24      0.9648 ± 0.0121
q5k                 1.6885    40.70      1.0249 ± 0.0120
```

Against 3.40–3.49× with the allowlist closed. The A/A control lands
0.53% off unity, so the per-mode deltas sit close to run-to-run noise:
this removes a 3.4× penalty, it is **not** a win over affine.

**The gates can fail, and were watched failing.** Closing
`nax_supports_mode` makes `kquant_nax_bench` panic (`q5k ran 3.4928x the
affine control, over the 2.0x ceiling`) and `kquant_mode_guards` panic
at its routing floor with every K-quant gap at 0 — while the affine
control holds 4.280e-4, which is what makes it a routing proof rather
than a tolerance check.

## Running Google's QAT checkpoint

The motivating case, and the first K-quant checkpoint here to reach a
forward pass. `gemma-4-12b-it-qat-q4_0-gguf` is 91.5% Q4_0 with a single
Q6_K embedding.

Getting it there needed the gemma4 layout fix listed under *Three fixes*
below: gemma4 interleaves sliding and global attention, and llama.cpp
marks `wv` `TENSOR_NOT_REQUIRED` because global layers take `V := Kcur`.
So the GGUF carries no `attn_v` on every sixth layer, and nothing in the
metadata names the period — the default `sliding_window_pattern = 5`
puts globals at 4, 9, 14…, while the real period is 6. Deriving
`layer_types` from which layers actually *have* an `attn_v` tensor puts
`full_attention` at exactly 5, 11, 17, 23, 29, 35, 41, 47.
`head_count_kv` is also an array here, which the scalar-only metadata
mapping had been dropping entirely.

**The import is 1:1 against the GGUF, checked exhaustively rather than
sampled.** Comparing the converted `model.safetensors` against the
source GGUF byte for byte, with a decoder transcribed from the repack
sites themselves:

| | compared | mismatches |
|---|---|---|
| Q4_0 codes + f16 scale bit patterns, **all 328 tensors** |
10,899,947,520 codes · 340,623,360 scales | **0 · 0** |
| Q6_K embedding, **all 3,932,160 super-blocks** | 62,914,560 int8
sub-scales · 3,932,160 `d` · 1,006,632,960 six-bit codes | **0 · 0 · 0**
|
| F32 tensors | 337 tensors, 3,079,360 B | **0**, and 0 dtype or shape
changes |

Nothing was requantized or dequantized anywhere in the file. Size
accounting closes with **residual 0**: the 15,710,744 bytes the import
lands below the GGUF are 15,709,720 bytes of GGUF metadata —
overwhelmingly the embedded 262,144-token vocabulary — plus 1,024 bytes
of `rope_freqs.weight`, which `gemma4_name_to_hf` drops on purpose. Two
conversions run from scratch are **SHA-256 identical**.

Norm dtype is preserved rather than chosen: the source stores its
non-quantized tensors as F32 only (`F32:338, Q4_0:328, Q6_K:1`), and the
default conversion emits F32. Passing `--dtype bfloat16` downcasts them,
costing fidelity to save 1,539,680 bytes; the figures in this
description are all from the 1:1 default.

Greedy, T=0, 320 new tokens:

```
"What is the capital of France?"            -> "The capital of France is Paris."
"17 sheep. All but 9 run away. How many?"   -> "The farmer has **9** sheep left."   (the trap answer is 8)
"List exactly three primary colors"         -> "Red / Yellow / Blue"                (format obeyed)
"Translate: The weather is nice today."     -> "Il fait beau aujourd'hui."
"Iterative nth Fibonacci in Python"         -> correct O(n)/O(1) loop, base cases, ValueError guard
```

Throughput on the dev box (M5 Max, greedy; the machine had been building
and converting, so these are a floor):

```
prefill_toks   ttft_ms   prefill_tps   decode_tps
        246       361         681.8        40.97
      5,820     4,836         898.0        35.58
     16,707    11,800         917.2        32.73
     41,094    34,448         706.1        19.45
```

## Symmetric Q4_0 / Q8_0: stop storing a derived array

Which then exposed the opposite of the problem this PR set out to solve
— the output was *larger* than the source, 7.12 GiB against 6.50 GiB,
and the K-quants were not the cause:

```
Q6_K embedding      (this PR's new path)   6.5625 bpw   ggml Q6_K = 6.5625   exact
Q4_0 everything else (pre-existing)        5.0000 bpw   ggml Q4_0 = 4.5000   +0.5
```

ggml's Q4_0 and Q8_0 are **symmetric**: `w = d·(q − Z)` stores one f16
scale per 32 weights and derives the offset. MLX affine is `w = scale·q
+ bias`, so the repack materialized a bias array in which every entry
was `−Z·scale` — 681 MB of pure redundancy on this checkpoint.

The converter now records `symmetric_zero_point` in `config.json` and
leaves the companion off disk; the loader rebuilds it with a
`mul_scalar` before any layer is constructed. No kernel change, no fork
change, no metallib rebuild — a full symmetric Metal mode is **deferred
behind a measurement, not rejected**.

The reconstruction is bitwise equal to what was stored, not merely
close: `Z` is a power of two, so the f16 product is exact for every
scale that occurs.

| check | result |
|---|---|
| stored bias vs `f16(−8·scale)`, raw uint16 patterns | 340,623,360
pairs, **0** mismatches |
| cases where `f16(−8s) ≠ f32(−8s)` | **0**, including 223 subnormal
scales at 2⁻¹⁵ |
| all 63,488 finite f16 patterns through `mul_scalar` | **0**
mismatches, at Z=8 and Z=128 |
| tensors dropped, before vs after | 1324 → 996, **every one** of the
328 an affine `.biases` |
| decode with the rebuilt bias | 237,895,680 elements, **all bitwise
identical** |
| Q6_K embedding across the change | weight, sub-scales and super-block
`d` all **byte-identical** |
| Q8_0 stored-vs-derived, against llama.cpp | 198 groups, 751,566,848
elements, **0** differing |

Both arms below are the same GGUF converted with the same options,
differing only in whether the bias is stored — the "before" side is
built by reverting `gguf.rs` + `convert.rs` to `8e72305d~1` (see
*Verification*), so the delta is the change and nothing else:

| | bytes | bpw |
|---|---|---|
| source GGUF | 6,975,877,728 | |
| before (bias stored) | 7,641,451,231 | affine 5.0000 · q6k 6.5625 |
| after (bias derived) | 6,960,166,984 | affine **4.5000** · q6k 6.5625
|

4.5000 is ggml's own Q4_0 density, so the import now lands 15,710,744
bytes *below* the GGUF it came from. The shrink accounts exactly —
`681,284,247 = 681,246,720` payload `+ 37,527` header — with no
residual, which is what rules out a payload having moved. Q8_0 goes
9.0000 → 8.5000, also exact. Q4_1 stores a real per-block minimum that
no scale can reproduce, so it keeps its biases and is untouched — of its
stored minima only 0.083% coincide with `f16(−8·scale)`, which is what
makes the distinction load-bearing rather than cosmetic.

The A/B that settles it: measured against llama.cpp's own decode, the
`Q8_0-symmetric` arm is digit-for-digit the `Q8_0-affine-control` arm
(140,014,524 bit-identical, 611,552,324 f16-rounding). Same source, one
arm storing the bias and one deriving it, indistinguishable. Greedy
generations match the pre-change checkpoint character for character,
markdown included.

**The cost, now stated in `mlx convert --help` and `docs/cli.md`.**
These imports are no longer mlx-lm-loadable, since mlx-lm requires a
stored `.biases` for affine groups — the same trade `--q-mode sym8`
already makes and already documents. It applies to **every** Q4_0/Q8_0
import, not only `--gguf-kquant`, because the decision keys off the ggml
tensor type. Q4_1 imports stay portable. Reading one on an mlx-node
build that predates the field fails loudly on first forward (`"Biases
must be provided for affine quantization"`), never silently — which is
why the marker is a *field* on `mode: "affine"` rather than a new mode
string: `parse_mode_str` returns `None` for an unknown mode and the
caller then falls back to guessing from checkpoint content, whereas an
unknown field is simply ignored.

## Does the feature work without the NAX tensor op?

**Yes — correctness is verified on a device that has no NAX kernels, and
it does not depend on them.** This mattered because the dispatcher's
tf32 escape only reroutes *float32* (`quantized.cpp:968` gates on
`enable_tf32() || x.dtype() != float32`), so bfloat16 and float16
`qmm_t` had always taken the NAX kernel on the dev box no matter how the
suite was run. Two independent checks, with different strengths:

**1. Real non-NAX hardware, every push.** CI runs on `macos-26-arm64`,
whose GPU is below the gen-17 floor `is_nax_available()` requires. On
run
[30165619618](https://github.com/mlx-node/mlx-node/actions/runs/30165619618)
(commit `fe26a026`, conclusion success): `kquant_mode_guards` **8
passed, 0 failed** in 36.24s and `kquant_ggml_parity` **8 passed, 0
failed** in 2.61s. `gpu_matches_cpu_on_every_quantized_matmul_kernel`,
`gpu_matches_cpu_for_every_activation_dtype` and
`gpu_matches_cpu_on_every_gather_kernel` all ran there against real
silicon. Being precise about what that log does and does not say:
libtest hides stdout without `--nocapture`, so the per-shape gaps are
**not** in it, and the runner's non-NAX status is *inferred* rather than
printed — `kquant_vs_affine_prefill` returned in 0.10s, which happens
only down the `!nax_available()` branch.

**2. Non-NAX dispatch on the dev box, where the numbers are visible.**
No escape hatch was added and nothing was rebuilt: `Device::Device`
parses the GPU generation out of `MLX_METAL_GPU_ARCH` rather than off
the hardware (`device.cpp:589-601`), so an existing upstream MLX
variable already reaches the gate. `MLX_METAL_GPU_ARCH=applegpu_g16s`
fails `gen >= 17` at `device.cpp:956` and turns every NAX branch off
in-process. Of the four places the Metal backend reads that generation
the other three test `== 13 || == 14`, `>= 15` and `< 15`, so they read
16 and 17 alike — a single-variable change. `kquant_mode_guards` then
prints its own state and passes 8/8:

```
nax=false tf32_gate=false
affine tf32 control gap 6.926e-7
smallest NAX qmm_t tf32 gap q6k 0.000e0 / q4k 0.000e0 / q5k 0.000e0
```

Every float32 K-quant `qmm_t` shape — all three modes, both alignments,
batched and unbatched, deep-K — reads `max |cpu − gpu| = 0.000e0`: the
simdgroup kernel is bit-for-bit equal to the CPU. The bfloat16/float16
`qmm_t` shapes, running on the simdgroup kernel for the first time on
this machine, land at worst `rel 6.41e-4` (float16, tolerance 4e-3) and
`rel 5.13e-3` (bfloat16, tolerance 3e-2). A second sweep at
`applegpu_g14s`, which additionally turns off `use_qmv_wide`, also
passes 8/8.

**Honest limits of check 2.** It flips *dispatch*, not hardware: the
simdgroup kernels really execute, and they are the same kernels a
non-NAX host runs, but the GPU underneath is still gen 17. And the
`#ifdef MLX_METAL_NO_NAX` preprocessor branch is not exercised by it —
that branch is a one-line `return false;` in the same function, so what
goes untested is the preprocessor, not the behaviour. Check 1 is what
covers real hardware; check 2 is what supplies the numbers.

**It found a real coverage hole, now closed.** `qmm_splitk`
(`quantized.cpp:1057`) has no NAX branch at all, so it is the simdgroup
kernel on *every* host — yet the dtype sweep's shapes all avoided
split-K, three by carrying a batch and two by having enough tiles that
`split_k` floors to 1. Twelve instantiations (3 modes × float16/bfloat16
× 2 alignments) had zero coverage anywhere, on any host, while
production reaches them on an ordinary single-sequence bfloat16 prefill.
They are covered now, at their own measured tolerances — split-K stores
each partition's partial in the *activation* dtype
(`quantized.cpp:1101`) before reducing, so bfloat16 spends 8 mantissa
bits per partial where the CPU keeps one float accumulator across all of
K; worst observed `1.12e-3` float16 and `5.99e-3` bfloat16, against
`6.4e-4` and `5.1e-3` for the same modes without split-K. All twelve
produce **byte-identical numbers on the NAX host, at `g16s` and at
`g14s`**, which is the evidence that this path is NAX-independent. No
existing tolerance was loosened.

## Scope

| | in | note |
|---|---|---|
| Q6_K / Q4_K / Q5_K | ✅ | consume only |
| Q4_0 / Q8_0 | ✅ symmetric import | value-lossless **and** ggml-sized —
see above |
| Q4_1, Q5_1 | ✅ pre-existing | genuinely asymmetric; stores a real
per-block minimum |
| Producing K-quants (`quantize()`) | ❌ throws | needs ggml's
`make_qkx2_quants` search |
| IQ4_XS | ❌ | a 16-entry non-uniform codebook, not a scale/bias grid —
does not share the kernel shape |
| CUDA | ❌ throws cleanly | Metal + CPU only |

## Known limits

- **The NAX matmul has still never run on a real weight.** Every perf
number above is on synthesised tensors. The QAT checkpoint above does
reach a forward pass, but its tensors are Q4_0 + one Q6_K, and Q6_K
lands on the embedding — a gather, not the `qmm_t` the NAX path serves.
A K-quant *matmul* on real weights still wants a Q4_K/Q5_K checkpoint
that loads; the pure-Q4_K fixture on hand is a Qwen3-0.6B whose
`model_type` routes to the dense family that never had a quantized path.
- **No llama.cpp *logit* parity.** What is proven is weight-level decode
parity — now both against llama.cpp's own decoder on pure-format files
and byte for byte against the QAT GGUF itself, on a model that runs.
Logits are still not compared. The converter emits neither tokenizer nor
chat template from GGUF metadata; `configSourceDir` supplies them from
the companion unquantized repo, which is how the QAT run above gets its
17,466-character jinja template, but that makes prompt assembly an input
to the comparison rather than something the two sides share by
construction. A greedy logit diff would need that pinned first.
- **The NAX *perf* gate is dev-machine-only, by decision — correctness
is not.** `kquant_nax_bench` is meaningful on exactly one host class:
`applegpu_g17s` on macOS ≥ 26.2. Elsewhere both arms fall back to the
same simdgroup kernel and the ratio means nothing, so it declines rather
than reporting a measurement — and libtest renders that decline as `ok`
without `--nocapture`. We are deliberately letting it skip on CI.
`KQ_NAX_REQUIRE=1` now pins **both** NAX-sensitive gates
(`kquant_nax_bench` and the NAX band inside `kquant_mode_guards`) and
turns the skip into a hard failure, so a host that silently stops being
a NAX host cannot report a green run with the whole band skipped.
Practical consequence: NAX *speed* coverage rides on a local run;
NAX-free *correctness* coverage runs on CI on every push.
- The multi-GB fixture gates (`kquant_realdata_llamacpp_parity`,
`symmetric_import_gemma4_qat`) are `#[ignore]`d rather than returning
early and reporting `ok`. **Both pass at this tip** against regenerated
fixtures (7/7, numbers under *Verification*), but they remain one-off
proofs rather than standing regression guards, because nothing in CI
supplies the fixtures. They previously counted as 7 green tests having
compared nothing; an unattended run now reads `0 passed; 7 ignored`.
Both are CPU-side import parity, so device-independent. The unset
variable is now the *only* skip: setting the root and having the
fixtures be gone — exactly how a checkout looks once the multi-GB files
are reaped — used to fall through to the same silent skip and report
`ok` to someone who had deliberately asked for the gate. A preflight now
names every missing path in one message instead.

- **No CI leg runs any of this PR's new suites, and the branch adds
none.** Verified rather than assumed: `git diff <merge-base>..HEAD --
.github` is empty, and `kquant`, `KQ_PARITY_ROOT`, `SYM_QAT_ROOT` and
`KQ_NAX_REQUIRE` each appear **zero** times under `.github/`. The e2e
matrix has per-family legs that download a checkpoint and run that
family's `#[ignore]`d tests; this PR adds two such suites and no leg.
Combined with the NAX gating above, every K-quant assertion needing
either a fixture or NAX hardware currently rides on a local run.
`kquant_ggml_parity` and `kquant_mode_guards` — the correctness core —
do run on every push.
- **`convert_model_inner` has no test entry point, so the conversion
pipeline is pinned only through the CLI.** Nothing in the crate calls
it. Concretely: the K-quant `.biases` cast skip,
`expand_symmetric_affine_biases` and `strip_symmetric_zero_point` can
each be deleted with the Rust suite still green. I proved this on my own
new test rather than inferring it — planting `|| false` over the
cast-loop skip leaves
`the_dtype_pass_preserves_kquant_biases_and_only_those` passing, because
it pins the classifier, not the wiring. The test comment says so.
Closing it needs a seam around the tensor-map passes.
- **`validate_existing_kquant_entry` is unreachable from any CLI
invocation.** `VALID_QUANT_MODES` excludes q4k/q5k/q6k and every
non-test `QuantEntry` uses an affine/mxfp/nvfp4/fp8 literal, so no
production path produces a K-quant mode string; both `format.mlx_mode()`
constructions sit after `#[cfg(test)]`. The rejection users actually hit
comes from the *affine* arm's `scale_is_float` check — which its sibling
test asserts by matching on `"affine storage"`. The function is correct
and cheap insurance if a K-quant mode ever enters that path, but its
three tests are not end-to-end coverage and should not be read as such.
- **A K-quant mmproj is not supported, in either flag position.** A
secondary output owns no `config.json`, so a K-quant tensor there has
nowhere to record mode/bits/group_size: with `--gguf-kquant` the
secondary-output guard refuses, without it the loader refuses, and the
Q6_K→BF16 fallback cannot rescue it (that path requires architecture
`gemma4` **and** name `token_embd.weight`). Forwarding the flag only
picks the more accurate of the two messages. Relatedly, the CLI converts
mmproj in a *second* native call, so an mmproj that trips the guard
leaves the primary output already written. On main that same path
silently produced vision weights with no config entry to describe them,
so this is fail-closed-but-late rather than a regression; a per-output
config is the real fix and is not in this PR.

## Three fixes that came along

All were found while trying to reach logit parity, and all are
pre-existing bugs rather than K-quant issues:

- **`fix(qwen3)`** — `model_type "qwen3"` has never had a
quantized-weight path, so a quantized checkpoint was decoded as dense
and surfaced as a wall of 198 shape mismatches. It now fails closed with
one named error. An affine Q8_0 import is rejected identically, which is
what proves this is family-wide and not a K-quant labelling bug. It
makes nothing work that did not work before; it makes the failure
legible.
- **`fix(gguf)`** — gemma4 attention layout is now derived from the
checkpoint rather than from a default period: `layer_types` from
`attn_v` presence, and `head_dim` / `num_key_value_heads` from the
per-layer `head_count_kv` **array** instead of dropping it. This is what
unblocks the QAT checkpoint. Proven by A/B to be pre-existing: the same
GGUF fails identically without `--gguf-kquant`.
- **`fix(gguf)`** — `head_dim` now comes from `attention.key_length` for
Qwen3-arch GGUFs, which decouple it from `hidden/heads` (128 vs 64 on
0.6B). Note this makes previously-converted Qwen3 artifacts stale;
`qwen3moe` is deliberately not in the set yet.

## What three adversarial-review rounds changed

Every finding was re-derived against the real control flow before being
acted on, and none of the 11 turned out to be a new defect of this
branch at the severity claimed. Chasing them still found three that no
round named — the useful part was the mechanisms, not the verdicts.

**One real regression, introduced here and now fixed.** Re-running a
conversion over its own output — `mlx convert -i out1 -o out2 -m
qwen3_5_moe -q --q-bits 4` — hard-failed on router gates. The no-recipe
skip arm validated an existing sidecar against the raw top-level
defaults and then continued past the point where the legacy per-key
policy runs, so `is_router_gate`, which pins routers to 8/64/affine,
never saw it. On a real `Qwen3.6-35b-a3b-UD-Q4_K_XL-mlx` checkpoint it
resolved bits=4, expected scales `[256,64]`, saw `[256,32]`, refused.
Only routers failed. Before that it exited 0 and wrote a config with the
router overrides dropped, which died later as an anonymous `null handle
returned: quantized_matmul` — neither behaviour is right. Both halves
now go through one shared `resolve_legacy_entry`, so the fresh path and
the skip arm cannot drift, and the skip arm records the override as well
as validating it. Recording is the half that fixes the round trip;
validating alone still ships the corrupt config.

**A synthesized gemma4 config no longer invents KV head counts.** With
the `head_count_kv` array both counts resolve. With a scalar, the global
count falls out of `pick`'s bounds check and — unlike the sliding count
— has no `.or_else`, so the loader silently reuses the sliding value;
with the key absent both default to 2. Convert succeeded, load succeeded
(the quantized path discards `out_features`, so nothing checks shape),
and the first `keys.reshape` threw inside `mlx_array_reshape`, which has
no try/catch while the binding is `extern "C-unwind"` — a process abort,
not an `Err`. Conversion now stops before the write with an error naming
the metadata key.

**One of my own comments was wrong and is corrected in place.** It
argued a mistyped layer "still fails loudly on its projection shapes"
via `head_dim` 256 vs 512. That holds for `layer_types` being wrong;
here `layer_types` and `head_dim` are correct and only `num_kv_heads` is
wrong — a different axis the argument never covered.

Each fix is pinned by a test whose mutation was planted and observed to
turn it red, rather than asserted to.

## A whole-branch review, and what it found

Three earlier adversarial rounds all reviewed *diffs*. This one read the
branch as a single artifact across four lenses — import, convert,
runtime, tests — which is the only way to see a helper added in one
commit and not applied in another, or a comment that was true when
written and false two commits later. Every finding was re-derived
against the real control flow; two were refuted and dropped.

**Re-converting a K-quant checkpoint wrote an unloadable one and exited
0.** The generic dtype pass classifies by dtype —
`Int8`/`Uint32`/`Uint8` is storage and never casts, anything float
follows `--dtype`. A K-quant `.biases` holds ggml's `d`, which *is*
storage, but its dtype is `Float16`, so it fell through and at the
default `--dtype bfloat16` lost three mantissa bits;
`resolve_kquant_group` demands exactly `Float16`, so the output then
refused to load. The GGUF importer already skipped both companions by
suffix — the SafeTensors half never got the rule, and gemma4, the family
that ships K-quants, is not in `owns_dtype_cast`.

**A pre-existing gemma4 pass was voiding a new guard.**
`ensure_kquant_storage_resolves_kquant` identifies Q4_K/Q5_K by a *pair*
— uint8 `.scales` beside a float16 `.biases`. The bf16 sidecar widener
runs 18 lines earlier, its filters do not exclude such a group, and it
rewrote the biases to Float32 — erasing half the signature, so the guard
returned `Ok` on exactly the drift it was written for.

**The affine-bias guard reached four gemma4 sites, not six.**
`router.proj` and the PLE embedding fail in the two different ways the
guard prevents: the router throws an anonymous null handle at load, the
PLE defers and throws on the first forward *after* load reports success.

**The mmproj rename stranded its sidecars.** This branch added
`rename_global_quant_group` for exactly that hazard and applied it in
two mappers; `gemma4_mmproj_name_to_hf` is the third and still matched
`.weight` only.

Plus: `--gguf-kquant` on SafeTensors input exited 0 having ignored the
flag; and two of my own comments overclaimed — the mmproj
`importKQuants` forward described an outcome no input can produce, and a
test doc called two sites "the last two" when four remained.

**One finding was refuted, one I got wrong and have since fixed.**
Refuted: that the widener/guard interaction yields silent garbage — it
throws, because `quant_super_ratio(Affine) == 0` activates MLX's
scales-vs-biases shape check and the 8:1 column ratio is
`astype`-invariant.

Wrong: I claimed the `Q4_0-symmetric` parity case's expectation was
satisfiable, arguing from the call site passing `out_dtype = 0`
(float32) that `d·q + (−8d)` is exact and only `q == 8` differs by sign
of zero. Sound arithmetic about an expression MLX does not evaluate —
its affine decode works in the dtype of `scales` and widens afterwards.
Measured with a probe feeding a known f16 `d` through `mlx_dequantize`
at `out_dtype = 0`: **16 of 32** elements differ from f32 `d·(q−Z)` at
4-bit, **31 of 32** at 8-bit, and every one equals the f32 value
*rounded to f16*. The original finding was right. A symmetric affine
case needs the f16 exemption **and** the signed-zero one (its `q == Z`
code makes ggml emit `−0.0` for negative `d`, and `−0.0` rounded to f16
is still `−0.0`), and the two were mutually exclusive — so
`Expect::F16RoundedModuloSignedZero` now permits both and the three
affine cases with a zero-crossing code use it. K-quant cases are
untouched: their scales are int8/uint8, so that decode genuinely does
run in f32.

One honest limit carried forward: the new classifier test pins the
*classifier*, not the wiring — `convert_model_inner` has no test entry
point, so the cast-loop skip, `expand_symmetric_affine_biases` and
`strip_symmetric_zero_point` are reachable only through the CLI. The
comment says so rather than implying coverage it does not have.

## Submodule

`crates/mlx-sys/mlx` moves `25176363` → `fef8890f` against main. (The
branch bumps it in 11 steps; an earlier revision of this description
quoted `98997bf1`, which is the second-to-last of those intermediates
rather than the base.) That fork branch was force-updated to its rebased
form; the pre-rebase tip is preserved at
`archive/pre-rebase-qwen-d256-sdpa`, which resolves to `25176363` —
exactly the SHA main pins — so every fork SHA pinned by this repo's
older commits stays fetchable. Both endpoints are branch-reachable on
`github.com/mlx-node/mlx`, verified with `git ls-remote` rather than
assumed. Everything after the NAX kernels — the non-NAX verification,
the QAT layout fix, the symmetric import and the gate commit — added
**no** fork commit. The submodule is unchanged by all of it.

## Verification

On the dev box (`applegpu_g17s`, NAX present), release, run serially:

```
kquant_ggml_parity                 8 passed
kquant_mode_guards                 8 passed
kquant_nax_bench                   1 passed    (table above)
symmetric_bias_parity              4 passed
cargo test --release --lib      2448 passed, 53 ignored
cargo clippy --all-targets -- -D warnings    clean
cargo fmt --check                            clean

# fixture-gated, #[ignore]d — 0 passed / 7 ignored without these
KQ_PARITY_ROOT=... kquant_realdata_llamacpp_parity -- --ignored   2 passed
SYM_QAT_ROOT=...   symmetric_import_gemma4_qat     -- --ignored   5 passed
```

**Both fixture gates were rebuilt from scratch and pass at this tip
(`b0edf37e`).** Their preflight was itself checked against every
broken-root state rather than by inspection — a non-directory root, an
empty root, and a half-present root each printed `ok` before and now
fail naming the missing paths.

The parity fixtures are six `llama-quantize --pure` files off one F32
Qwen3-0.6B, each verified to be genuinely single-type before use (198
tensors of exactly the claimed type, `F32:113` otherwise) — a fixture
that had quietly stayed mixed would pass for the wrong reason. Per
format, 751,566,848 elements:

```
q4k                    751,566,848 bit-identical   hard 0   zero-sign 0            f16-round 0
q5k                    751,566,848 bit-identical   hard 0   zero-sign 0            f16-round 0
q6k                    741,668,535 bit-identical   hard 0   zero-sign 9,898,313    f16-round 0
Q8_0-affine-control    140,014,524 bit-identical   hard 0   zero-sign 0            f16-round 611,552,324
Q4_0-symmetric         707,072,815 bit-identical   hard 0   zero-sign 44,494,033   f16-round 0
Q8_0-symmetric         140,014,524 bit-identical   hard 0   zero-sign 0            f16-round 611,552,324
Q4_1-asymmetric        516,387,327 bit-identical   hard 0   zero-sign 0            f16-round 235,179,521
Q8_0 stored-vs-derived    198 groups, 751,566,848 elements, 0 differing
```

`symmetric_import_gemma4_qat` reports `old 7,641,451,231 B → new
6,960,166,984 B`, `shrink 681,284,247 = 681,246,720 payload + 37,527
header`, `affine bpw 4.5000`, 328 dropped tensors all `.biases`,
237,895,680 decoded elements bitwise identical, and the q6k embedding
byte-identical across the change.

**Rebuilding the two pre-symmetric fixtures.** Current code cannot emit
them — the symmetric drop applies to every Q4_0/Q8_0 — and synthesizing
`.biases = −Z·scales` would make the A/B compare a reconstruction
against itself, so it is not done that way. With a clean tracked tree,
`git checkout 8e72305~1 -- crates/mlx-core/src/utils/gguf.rs
crates/mlx-core/src/convert.rs` (those two files alone still compile
against this tip), `yarn build:native`, convert, then restore both files
and rebuild. The result carries no `symmetric_zero_point` and 707 / 1324
tensors against 509 / 996 — one `.biases` per quantized tensor, which is
the structural check that it really is the old behaviour.

The QAT checkpoint converts to 6,960,166,984 bytes with `full_attention`
at `[5,11,17,23,29,35,41,47]`, `symmetric_zero_point` 8,
`num_key_value_heads` 8 and `num_global_key_value_heads` 1, and answers
Paris / 9 / Red-Yellow-Blue.

Same tree with the tensor op out of the picture:

```
MLX_METAL_GPU_ARCH=applegpu_g16s  kquant_mode_guards   8 passed   (nax=false tf32_gate=false)
MLX_METAL_GPU_ARCH=applegpu_g16s  kquant_ggml_parity   8 passed
MLX_METAL_GPU_ARCH=applegpu_g14s  kquant_mode_guards   8 passed
MLX_ENABLE_TF32=0                 kquant_mode_guards   8 passed
```

And both directions of the new fuse, exercised rather than assumed:

```
KQ_NAX_REQUIRE=1                                   8 passed          (NAX host)
KQ_NAX_REQUIRE=1 MLX_METAL_GPU_ARCH=applegpu_g16s  7 passed, 1 failed in 0.83s
```

The bump, `kquant_mode_guards.rs` and `kquant_nax_bench.rs` are **one
commit** by necessity: it is a two-way lock. The old test drives four
`qmm_t` cases at `F32_TOL = 1e-5`, and once the allowlist is open those
take the tensor op and gap ~1e-4; the new test's `NAX_TF32_GAP_FLOOR`
asserts the gap is *non-zero*, which the old kernels cannot satisfy. No
ordering splits them without a red bisect point. The follow-up split-K
commit is test-only and touches no fork SHA, so it stands alone as a
bisect point.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01GJ84M8sPwELGujxRZsuN3s


<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Touches quantization import, conversion, and load paths across
multiple model families; incorrect metadata or bias handling would
produce unloadable checkpoints or silent mis-decode, though the PR adds
extensive validation and tests.
> 
> **Overview**
> **K-quant path:** GGUF import gains `importKQuants` / `--gguf-kquant`
to repack Q4_K, Q5_K, and Q6_K without dequantizing. `quant_dispatch`
adds `q4k`/`q5k`/`q6k` modes, shared `resolve_kquant_group` validation,
and load-time guards; Gemma4, LFM2, and related builders wire K-quant
linear/switch/embedding paths. A vendored ggml decoder is compiled at
build time (`-ffp-contract=off`) for K-quant parity tests.
> 
> **Symmetric Q4_0 / Q8_0:** Imports can record `symmetric_zero_point`
in `config.json` instead of storing derived `.biases`.
`expand_symmetric_affine_biases` rebuilds companions at load and at
convert input; `strip_symmetric_zero_point` drops the claim from emitted
configs so re-converts stay loadable.
> 
> **Convert / re-convert:** Legacy quantization decisions are
centralized in `resolve_legacy_entry` so fresh quantize and
skip-already-quantized paths agree (fixes router-gate overrides on
second-pass convert). Re-converting mismatched geometry or K-quant
groups without a recipe is rejected; K-quant f16 `.biases` are excluded
from the dtype cast pass. Dense **Qwen3** fails closed when a non-empty
`quantization` block is present.
> 
> **Other:** MTLB min-OS parsing treats minor and update as separate
bytes (fixes macOS 26.5.2 floor checks). MTP disables K-quant heads the
same way as sym8.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
b0edf37. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
`docs/cli.md` covers how to invoke `mlx convert`; nothing covered what it
actually does. This adds the internals doc for contributors adding a
quantization mode or debugging a bad conversion.

Contents:
- on-disk format table for every mode (affine, mxfp4/8, nvfp4, fp8_e4m3,
  sym8, ggml q6k/q4k/q5k, and the Q4_0/Q8_0 derived-bias scheme), each with
  its decode equation, companion-array shapes, and derived bpw
- the per-tensor decision engine: recipe x tensor-class matrix, the
  `--q-mxfp` upgrade arms, and the two decision-scoping traps
- GGUF import: source-type routing, name maps, what is dropped, and the
  `--config-dir` contract
- SafeTensors families, foreign formats, MoE/VLM/MTP specifics
- `config.json` provenance and the loader reconstruction contract
- imatrix/AWQ pre-scaling and FP8 activation calibration
- 43 numbered gotchas: silent defaults, silent losses, flags that do less
  than they look like, and validation that fires too late

Researched across 6 dimensions with an adversarial verify pass; 38 claims
were refuted and corrected before writing. All 296 `file:line` citations
resolve unambiguously and none point past EOF.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01D71YgNf6FuENWHn7VHvL7f
… paged persist-cache (#100)

## `mlx dashboard` — local web dashboard for models, sessions, metrics,
and the paged persist-cache

Adds an `mlx dashboard` subcommand: a local, single-user web UI (Node
`http` + a React SPA) over the on-disk `~/.mlx-node` workspace. It ships
with the mlx npm packages and never links the native GPU addon.

### Four capabilities
1. **Local model management + remote downloads** — discover installed
models, size them, delete them (path-safe by name); pull new models from
the catalog with atomic, revision-pinned, resumable downloads (staged →
verified → published with a completion marker).
2. **Session history management** — ingest pi session JSONL (both the
`--cwd--/` and flat `--session-dir` layouts), browse/rename/delete
sessions, view transcripts.
3. **Metrics for history sessions** — per-session and global
token/throughput charts sourced from a default-on metrics-trace JSONL
sink (incremental-by-mtime ingest into a disposable SQLite index),
including delegated subagent turns.
4. **PagedAttention persist-cache metrics/management** — an opt-in,
fail-open SSD "cold tier" that persists prefix blocks across restarts
for **four model families**, plus dashboard views to inspect and
clear/evict it.

### Architecture
- **Phase A (native):** wires a cold tier into paged inference
(`crates/mlx-paged-attn` + `crates/mlx-core`), content-addressed and
fingerprint-guarded; opt-in via `persistPagedCache`, fail-open (a failed
restore just does a normal prefill). A bounded background writer with a
shutdown drain barrier (`coldCacheDrain`) flushes queued blocks on `mlx
agent -p` exit.
- **Phase B (agent):** a default-on `MetricsTrace` JSONL sink +
`persistPagedCache` default for every allowlisted family (with
`--no-persist-cache`).
- **Phase C (dashboard package):** `@mlx-node/dashboard` — a `node:http`
route table with a loopback-only mutation guard, SSE download progress,
a drizzle/`node:sqlite` disposable index rebuilt from JSONL/disk, and a
Vite + React 19 + Tailwind SPA. `mlx dashboard [--host --port
--session-dir --no-open]`.

### Cold tier: four families, not one

`qwen3` dense is the only non-hybrid family — its paged pool covers
every layer. The three hybrids keep state *outside* the pool, so each
persists it as a separate `ColdSidecar`: gemma4 a sliding-window
`RotatingKVCache`, qwen3_5 dense/MoE a GDN recurrent state. The descent
that finds one (`deepest_backed_boundary`) is vLLM's
`MambaManager.find_longest_cache_hit`; where we differ we are stricter,
and unlike vLLM's filesystem tier this one is built for reuse *by a
later process*, so it carries fingerprints, payload checksums,
version-skew rejection and a real `fsync(2)`.

Why there is no RAM tier at all, and why the disk hop gets *cheaper* as
models grow, is recorded in `docs/architecture.md` under "Memory model:
unified memory decides the cache hierarchy".

### The reachability bug this branch fixes

Capture anchored its only sidecar at `floor(P/16)*16`, while a restore
of the same prompt can only ever name `floor((P−1)/16)*16` — the lookup
is capped at `prompt_len − 1` so a prefill always keeps a suffix token
to forward. The two agree **unless P is an exact multiple of the block
size**, where capture lands exactly one block deeper than anything the
read side can spell.

```
P=6572 (ragged)   capture 410 blk   restore ceiling 410   boundary 6560   REACHABLE
P=6576 (aligned)  capture 411 blk   restore ceiling 410   boundary 6576   UNREACHABLE
```

An aligned prompt wrote a structurally valid ~210 MB sidecar to an
address nothing could name, then self-locked: the next capture
recomputed the same key, `contains_in` reported it present, and returned
without trying anything shallower. Raising the capture budget made it
*worse*, because a chain that completes in one turn writes only that
unreachable boundary.

Measured on real weights (`Gemma-4-26B-A4B`, aligned 8992-token prompt,
one-shot budget): **0 → 8976 cached tokens (99.82%), TTFT 2435 → 608
ms**, output byte-identical across 16 turns with the tier on and off.
The fix clamps the capture ceiling to the deepest boundary a restore
enumerates — the rule qwen3_5's GDN ladder already followed; gemma4's
sliding prompt boundary was the one publisher rounding the other way.

### Observability

The failure above was invisible: a restore that *declines* counted
neither a hit nor a miss, so a dead tier and a healthy one produced the
same all-zero row, and the UI rendered "no lookups recorded" — which
reads as *nothing ran*, not *reuse refused*. Nothing counted a write
that never landed either.

Added `write_errors`, `restore_declines` and `restore_suppressed`, split
`queue_drops` (admission refusals) from write failures, and surfaced all
three through the metrics trace, the API and the cold-tier health card.
Dashboard schema 3 → 4.

### How it was built
Executed via subagent-driven development as a single PR: **19 tasks**,
each implemented + tested by a fresh subagent. Followed by an extensive
whole-branch adversarial-review loop — **3 full whole-branch rounds + 5
fix-delta confirmation rounds** — every finding independently verified
by control-flow analysis before being fixed or documented as an accepted
fail-open/display-only residual.

The cold-tier extension and the fixes above went through a further
multi-agent cycle: end-to-end validation on real weights across all four
families, then diagnose → fix → whole-branch review → close-findings →
gates. Every new test carries a named mutation that was applied, shown
red, and restored.

One diagnosis was **refuted by measurement after being "verified" by
code reading** — an all-or-nothing suppression guard whose arithmetic
matched the observed brackets exactly but which never executes on the
cold path (0 of 17 traces; disabling it is a byte-for-byte no-op). The
real cause was the one-block rounding disagreement above, on the
opposite side of the tier. Worth knowing if you are reading the
suppression code and wondering why it is untouched.

### Testing

Gates on the final tree, run serially on an otherwise idle machine:

| gate | result |
| --- | --- |
| `cargo fmt --check` | clean |
| `cargo clippy --all-targets -- -D warnings` | zero warnings |
| `cargo test -p mlx-core --lib` | 2598 passed / 0 failed / 56 ignored |
| `cargo test -p mlx-paged-attn` | 13/13 suites, 0 failed |
| `yarn typecheck` | clean |
| `vp lint --type-aware --type-check` | pre-existing warnings only |

Real-weights end-to-end, all four families: cross-process restore,
session resume (a planted passphrase returned by a **new** process, not
merely exit 0), fork isolation proven by the parent file's SHA being
unchanged, and persist-off parity SHA-compared rather than asserted.

Docs: `docs/dashboard.md` (usage, data sources, security model, accepted
residuals), `docs/paged-cache.md` (support matrix, parity gates,
counters), `docs/architecture.md` (memory model).

### Notes for reviewers

- The cold tier is opt-in and fail-open; the SQLite index is disposable
(rebuildable). Non-loopback bind is a documented full-exposure mode with
a loud warning.
- **The failing TS gates are missing fixtures, not code.**
`data/openai-gsm8k` is listed in `.git/info/exclude` and lives only in
the primary checkout, and worktrees do not inherit untracked files.
Every failure is GSM8K or a local Qwen tokenizer; none is in
`dashboard`, `agent` or the cold tier, and no changed file sits in those
paths.
- **Rebased onto current `main`**, which now carries the native ggml
K-quants from #101. Two conflicts, both resolved by inspection: a test
module both sides appended independently (kept both), and a convergent
fix of the same min-OS byte-split bug (took main's, ours became empty).

Known gaps, stated rather than buried:

- **Verified post-fix on four checkpoints**, each with a prompt whose
`promptTokens % 16 == 0` read off the wire (not assumed), so the aligned
case the fix targets was genuinely exercised:

| checkpoint | family | proof |
| --- | --- | --- |
| `gemma-4-26b-a4b-nvfp4-mlx` | gemma4 | sidecars at
1024/4096/6144/**6304**, none at 6320; 394 hits, 0 misses, 99.7% |
| `qwen3.6-27b-unsloth-mxfp4-mlx` | qwen3_5 dense | boundary 6384 =
`floor((6400-1)/16)*16`; 99.75%, 399 hits |
| `agents-a1-unsloth-mxfp4-mlx` | qwen3_5 MoE | boundary 6320 =
`floor((6336-1)/16)*16`; 99.75%, 395 hits |
| `qwen3-0.6b-mlx-bf16` | qwen3 dense | 1360 = `floor((1376-1)/16)*16`
in one hop, `coldMisses` strictly 0 |

`6304` is the load-bearing number: the pre-fix rule would have anchored
that prompt at `6320/16*16 = 6320`, which no restore can name. Hybrids
installed a sidecar on every restoring turn, so no unsound block-only
restore occurred.

- **`gemma-4-12b-qat-kquant-mlx` does not load** — `Missing required
weight: layers.5.self_attn.v_proj.weight`, reproducible. Absent `v_proj`
on global layers is normal for gemma4, but this config declares no
`layer_types` / `attention_k_eq_v` / `num_key_value_heads`, so the gate
that would skip it cannot fire; the directory holds only `config.json` +
`model.safetensors` with no tokenizer. A mid-conversion dequant
artifact, not a branch defect.

- **gemma4 *dense* has no coverage.** The family path is exercised by
the 26B MoE checkpoint only. Read "gemma4 verified" as "gemma4 MoE nvfp4
verified". K-quant x cold tier likewise remains untested.

- **Persist-off parity is only meaningful for short forced answers.**
Decode is nondeterministic with the tier *off* (gemma4 preset is
temperature 0.7, no seed flag): two `--no-persist-cache` runs on one
prompt produced 1499 vs 1808 bytes. SHA parity was proven over forced
answers up to ~50 tokens; a free-form parity gate cannot fail in either
direction until sampling is pinned.

- **No pre-fix A/B was run on this machine.** The passes rest on the
arithmetic identity above (deepest anchor landing on
`floor((P-1)/16)*16` with nothing at `P`), not on a before/after
comparison.

- **Full restore depth costs ~4 turns at the default capture budget**
(128 blocks/turn), during which a ~6.3k-token prompt sits at ~25% reuse.
`MLX_COLD_CAPTURE_BLOCKS_PER_TURN=1024` converges in one turn with no
corruptions. Whether the default should scale with prompt length is a
product call, flagged not changed.

- **Self-heal from an already-poisoned cache root was not observed on
hardware.** Under the fix the ceiling never proposes the bad boundary,
so healing is structural; constructing the poison would have needed the
pre-fix binary.

- **The growing-conversation cost of the ceiling clamp is unmeasured.**
It gives up this turn's generated region; turn N+1's own ceiling covers
it, but every validation run was single-turn.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Touches inference KV identity, cross-process restore correctness, and
weight fingerprinting—errors could cause silent wrong-prefix reuse or
block persistence; CI changes reduce but do not eliminate that class of
risk.
> 
> **Overview**
> Adds a **process-wide SSD cold tier** for block-paged KV (and hybrid
**sidecar** state for gemma4 sliding-window and qwen3_5 GDN), wired
through new `cold_tier` in `mlx-core` with fail-open opens, per-turn
capture budgets, and **content-bound fingerprints** that require weights
to be materialized first via a new **`WeightsResident`** witness from
`materialize_weights`.
> 
> **Native/JS surface:** `persistPagedCache` on several model configs,
`coldCacheStats` / `coldSidecarStats` / `coldCacheDrain`, and allowlist
helpers (`coldRestoreFamilies`, `gdnPrefixCheckpointLimit`). **`sha2`**
backs full-shard digest fallback when the dashboard download marker does
not fully pin shards.
> 
> **CI/publish:** `MLX_TEST_REQUIRE_METAL` on the main test leg;
**cold-tier parity** and **qwen3_5 ladder** ignored lib tests on
model-e2e with pass-count and skip grep guards; publish runs **`yarn
workspace @mlx-node/dashboard build:ui`** so the SPA ships; dashboard
`web/` build output is gitignored; docs link **`docs/dashboard.md`**.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
6ebb039. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <[email protected]>
Both e2e failures on `main` this week, fixed at the cause. Neither
needed a retry.

```
d0b608f  qwen3_5-dense  qwen3_5_cold_tier_restart_parity
e59d78e  lfm2           lfm2_paged_delta_memory_probe_parity   (a DOCS-ONLY commit)
```

## 1. The cold-tier gate was not flaky — it was broken

It entered the e2e leg in `d0b608fa`, and **e2e is skipped on PRs**, so
it first executed on main and failed. It reproduces **4/4 locally**.

A capture turn anchors exactly ONE sidecar, at the deepest rung it
reached. The fixture needs several turns to reach the frontier, so that
the shallow rungs a diverged restore prompt can name actually get
written. That held for free while the walk stopped wherever the writer
queue refused (~12 blocks). `1faa7154` replaced that with a real policy
— 128 blocks / 250 ms — in the same PR, and 128 never binds on a
1259-token prompt:

```
cold_capture_walk blocks=80 enqueued=80 stop=end elapsed_ms=119.775
                                        ^^^^^^^^ ran out of PROMPT, not budget
```

At 1.5 ms/block a machine has to be **2.1× slower** for this to pass.
That was the whole pass/fail axis.

Pinned to 12 blocks / 60 s. The deadline is not a lengthened timeout —
with the block budget below the prompt's block count the walk stops on
`Budget` every time, which removes the clock from the outcome rather
than making it less likely to matter.

```
before   warm-up 2 cached=1248 (deepest rung)   restore anchored at 0     FAIL
after    warm-up 2 cached=64                    restore anchored at 304   ok   (4/4)
```

Added the invariant that silently rotted, so this cannot recur quietly.
Restoring the 128 default now fails as *"FIXTURE, not a product fault: 3
capture turn(s) × 128 blocks × 16 tok = 6144 tok of reach, which covers
this prompt's deepest ladder rung"* — instead of "cold restore did not
engage", which pointed the reader at the restore path for a fixture
fault.

Two counters that misled the diagnosis, noted in the commit for the next
reader: `installed` is a **restore-side** counter (so `installed=1` was
instance 1 loading its own sidecar, and said nothing about durability),
and `restore_suppressed` has exactly one production site which is
**gemma4-only**. The drain barrier is sound.

## 2. The lfm2 probe had an unstable oracle

The arm under test was correct; the control failed for reasons unrelated
to caching.

`ChatResult.text` is not the generation — it is the post-`</think>`
remainder, and two scrubber branches return `""` for a perfectly correct
turn. Both reproduce on this checkpoint with real weights
(`num_tokens=512 reasoning_tokens=512 text=""` beside a 2079-byte
`raw_text`). The old comment claimed the 128-token budget "force-closes
a looping `<think>` deterministically"; it does not — the force is gated
behind `!is_terminal`, so an EOS on the consuming step drops it.

Assertions moved to `raw_text` (the verbatim decode; empty only when
`num_tokens == 0`, which stays fatal). And the flat arm was a *second
free-running oracle*, not a control — each arm generated its own
replies, so by turn 3 they were answering different conversations, 102
tokens apart on the failing run. The control now runs over the paged
transcript.

Stated cost: the control no longer drives `chat_session_continue`, so it
no longer exercises flat prefix reuse. That coverage is pinned
byte-exactly by `lfm2_paged_vs_flat_prefix_reuse_parity` (`r2_flat.text
== r2_paged.text` on a delta turn).

## Proof

| | |
|---|---|
| cold tier | 4/4 fail before, 4/4 pass after, `anchored at 304` every
run |
| fixture guard | restoring 128 → the FIXTURE message, not the
misleading one |
| lfm2 | full file **8 passed** |
| lfm2 still bites | `supports_delta: true → false` → *"paged delta turn
2 lost the turn-1 context: expected the sum 18"* |
| gates | `cargo fmt --check` 0, `cargo clippy -p mlx-core --all-targets
-D warnings` 0 |

Carrying `model-e2e` so the legs actually run here — the gap that let
this land in the first place.

## Not fixed here

Because a turn writes only the deepest rung it reaches, **no prompt
shorter than `128 × block_size` = 2048 tokens ever gets a shallow rung
written**, so a next prompt that diverges gets zero reuse instead of
reconciling down. Same shape as the recorded gemma4 "<1024-tok prompts
get ZERO reuse" gap — a design tradeoff (sidecars are 18–75 MiB), not a
flake, and it deserves its own decision rather than a reactive change.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01VKtaz9j1ih1YtSPBf5TtQm

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches process-global cold-cache initialization and CLI download
behavior (retries re-fetch partial shards from byte 0); production
default capture policy unchanged except new optional install APIs used
by tests.
> 
> **Overview**
> Makes **cold-tier restart parity** and **LFM2 paged-delta memory** e2e
gates deterministic, and adds **transient retry** for `mlx download
model`.
> 
> **Cold tier:** Adds `install_cold_capture_budget` /
`install_cold_cache_root` (and `installed_cold_cache_root`) so harnesses
pin process-global `OnceLock` state without `setenv` on multi-threaded
tokio tests. Repeat installs with the same values succeed; conflicting
values and unopenable roots return `false`. The parity harness pins **12
blocks / 60s** capture budget (so one turn cannot walk the whole
prompt), asserts fixture reach vs ladder depth, checks **write_errors**
before restore assertions, reuses the tier root across two gates in one
process (no `remove_dir_all` on the pid-scoped path), and adds unit
tests for idempotent install and stable inode across double
`prepare_cold_root`.
> 
> **LFM2:** Memory probe asserts on **post-`</think>`** `raw_text` via
`answer_surface` and `states_number` (not empty `ChatResult.text`). Flat
control is rebuilt from the **paged transcript** with
`chat_session_start`; adds flat-only `chat_session_continue` probe
**(d2)**. Streaming session tests gate on **`cached_tokens`** / uncached
prompt growth instead of TTFT ratios.
> 
> **CLI:** `withRetries` / `isRetriableFetchError` wrap per-file and
listing downloads (5xx, 429, 408, transport; not ENOSPC/403/protocol
refusals), with 1s/2s/4s backoff and Vitest coverage.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
e0140df. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 5 <[email protected]>
## What changed

- add a fail-closed fixed Unsloth selector for the exact SafeTensors
Gemma 4 26B-A4B MoE shape
- emit 180 MXFP4/NVFP4 dense and expert FFN modules plus 115
MXFP8/plain-E4M3 attention modules
- keep routers, embeddings/head, norms, vision/audio, and unmatched
tensors in BF16
- add Gemma rank-2 plain E4M3 loading via one-time BF16 reconstruction
while keeping stacked experts fail-closed
- include plain-E4M3 BF16 reconstructions in cache-limit weight
accounting (2,220,359,680 bytes for the published map)
- preserve the calibrated legacy fallback for unsupported Gemma4
wrappers while rejecting uncalibrated fallback
- update CLI messaging and docs to distinguish the existing Qwen
final-eight policy from Gemma's all-low-FFN policy

## Why

The CLI accepted `--q-recipe unsloth --q-mxfp` and `--q-mode nvfp4` for
Gemma, but the backend only selected the verified Qwen map. Gemma
therefore fell back to the legacy Dynamic 2.0 predicate, and its loader
rejected the plain E4M3 attention weights required by the DGX class map.

## Validation

- `cargo check -p mlx-core --lib`
- `yarn vp test packages/cli/__test__/convert-cmd.test.ts` (25/25)
- `yarn build:ts`
- `cargo fmt --all -- --check`
- `git diff --check`
- GitHub Actions at `8c8b270e`: Build, Rust Lint, full `cargo test`,
TypeScript build/tests, and Publish all passed
- regression coverage pins the exact reconstructed-BF16 byte delta and a
dense zero-delta control
- rebuilt the release native addon
- converted the real `google/gemma-4-26B-A4B-it` checkpoint with
matching Unsloth imatrix into both maps
- audited exact 180 low / 115 high classes and SafeTensors index closure
- loaded both artifacts and generated deterministic one-token `OK`

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches quantization recipe selection, conversion validation, and
Gemma4 weight loading/memory accounting; wrong gates could reject valid
checkpoints or mis-classify tensors, but behavior is heavily gated and
covered by new tests.
> 
> **Overview**
> Extends the verified **fixed Unsloth** path beyond Qwen hybrids to the
exact SafeTensors **Gemma 4 26B-A4B MoE** checkpoint (`--q-mxfp` /
`--q-mode nvfp4`). `OfficialUnslothRecipeKind` is split into Qwen vs
Gemma4 variants so Gemma never inherits Qwen’s final-eight FFN
promotion.
> 
> **Conversion (`convert.rs`):** Strict gates on config, `--model-type
gemma4`, MoE dims, and a 180-MLP / 115-attention tensor inventory;
near-miss Gemma inputs **fail closed** instead of falling back to legacy
Dynamic 2.0. Gemma’s map keeps all dense/expert FFNs low, attention
q/k/v/o high, and everything else BF16. A pre-quant **shape preflight**
enforces ranks, K%32, and the 180/115 class counts.
> 
> **Runtime (Gemma4):** Rank-2 **plain E4M3** attention weights load via
one-time BF16 reconstruction and A16 matmul; experts stay NVFP4-only.
Reconstructed FP8 weight bytes are folded into cache-limit accounting.
> 
> **CLI/docs/tests:** Help text and docs describe Qwen vs Gemma
policies; CLI tests updated for the new messaging.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
8c8b270. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
…erence sidecar (#103)

Turns mlx-node into a signed macOS app: a tray icon, an Admin window,
and a supervised inference server that Claude Code / Codex connect to
over HTTP. No terminal required.

`mlx dashboard` is **retired** — its HTTP layer is deleted, not adapted.
The dashboard is now the app's Admin window, reached over `app://` + a
`MessagePort`. There is no TCP port except the inference server's, which
exists for external clients.

## Architecture

```
mlx-node.app
│
├─ MAIN  (ESM entry)                                     must NEVER block
│    Tray ●  status · Start/Stop server · Open Admin · Quit
│    BrowserWindow "Admin"  ←  app://  →  Contents/Resources/www
│    supervisor · broker (hands over a port, then leaves the data path)
│
├─ ADMIN  utilityProcess                         no addon · no Metal
│    @mlx-node/dashboard as a LIBRARY · node:sqlite + drizzle on its own thread
│    ⟵ MessagePort ⟶ renderer
│
└─ INFERENCE  utilityProcess               233 MB native · Metal · bearer auth
     @mlx-node/server createServer() → TCP, for EXTERNAL clients only
```

Three processes because a blocked main freezes the tray, the menus and
all IPC. Measured with an identical 3s synchronous block in each
location:

| | block in ADMIN | block on MAIN |
|---|---:|---:|
| main event-loop max lag | **3 ms** | **2960 ms** |
| IPC round-trips completed | **29** | **0** |

## Why Electron

Measured, not assumed. napi-rs v3 ships `dyn-symbols`, so `nm -u` shows
zero undefined `napi_*` symbols and **no electron-rebuild is needed** —
`NODE_MODULE_VERSION` is a V8-ABI check Node-API never reaches.

```
Electron 43.2.0 · Node 24.18.0 · process.versions.napi = 10
addon dlopen under hardened runtime      PASS
20x 2048³ fp32 matmul   Electron 21.47 TFLOP/s == plain Node 21.47 TFLOP/s
                    DMG        installed
oMLX               786 MB       1.6 GB     bundled CPython + MLX layer
mlx-node.app      ~180 MB       508 MB     utilityProcess reuses Electron's Node
```

`electron#44291` (PartitionAlloc capping `posix_memalign` at ~2 GB,
which broke llama.cpp in LM Studio) does not apply: MLX allocates
through `MTLDevice::newBuffer` → IOKit.

## Server changes (all pre-existing gaps a CLI could tolerate and an app
cannot)

- `/health` was a constant `{status:'ok'}` stub → real readiness, and
the last load error is now retained
- `close()` hung for the full remaining generation on an open SSE stream
→ bounded close + force-close, idempotent
- Zero auth → bearer / `x-api-key` at the single choke point
- Out-of-band model load raced the drain timer and the Metal allocator →
holds the drain suspension and the writer lock
- No `mlx serve` → added, sharing the sidecar bootstrap with
`launch-claude`

## Packaging

`@electron/packager` with explicit Mach-O signing. The native payload is
three files that **must** be colocated (`mlx.metallib` loads next to the
binary; `paged_attn.metallib` resolves `dladdr`-relative), placed
verbatim in `Contents/Resources/native/` outside asar, because `dlopen`
cannot read an asar archive.

The release gate asserts something `codesign` does not: **every Mach-O
has a TeamIdentifier**. An unsigned Mach-O under `Contents/Resources`
passes `codesign --verify --deep --strict` locally and is rejected by
the notary hours later.

Bundle went 993 MB → **566 MB** by excluding 7 cloud LLM SDKs
unreachable without a `pi-ai` `stream()`, and the clipboard prebuilts
that leak a build path.

## What's in this last round (UI)

Three defects that all read as "the app feels janky", each measured
against the real Admin window over the Chrome DevTools Protocol rather
than inferred:

**Skeletons didn't match the boxes they stood in for.** `h-8` against a
30px line box, `h-4` against 20px, 4 skeleton rows against 6 real ones
(−168px), and both tables rendered *no* `<thead>` while loading and a
real one after. Text bars are now `h-[1lh]` inside the element carrying
the font classes — one line box by construction. Verified in the shipped
runtime (Chromium 150): `1lh` = 20px under `text-sm`, 30px under
`text-3xl leading-none`.

**Every tab switch reloaded an already-loaded page.** React Router
unmounts the route, so each visit restarted from `data === undefined`.
`useJson` now serves from an LRU and revalidates behind it.

**Metrics could never hit that cache** — it put `Date.now()` in its
request path, which *is* the cache key, inside a memo that re-runs on
every mount:

```
tab        cache   settled
Overview   HIT      20ms
Models     HIT      48ms
Sessions   HIT      27ms
Metrics    MISS    154ms   ← every visit, both laps
Cache      HIT      42ms
```

**Two scrollbars on Metrics.** The shell was `min-h-screen` (document
scrolls) with `main` also `overflow-auto` — two nested scroll
containers. Only Metrics exposed it, because recharts positions a legend
`absolute`, adding 117px to `main`'s scrollHeight without growing its
box.

## Verification

```
vp test --run          2869 passed / 21 skipped, 0 failed
yarn typecheck         0        (three projects it was silently skipping now covered)
vp lint --type-aware   0
cargo clippy/fmt       0
packaged .app          gate green: every Mach-O carries a TeamIdentifier
```

The suite first came back with one failure,
`packages/agent/__test__/cold-counter-fields.test.ts`, which turned out
to be a **stale local artifact rather than anything on this branch**.
That test compares the native addon's runtime counter keys against
`COLD_COUNTER_FIELDS`, and the working copy's `.node` was from Jul 28 —
before `restoreDeclines` / `writeErrors` existed, though the generated
`index.d.cts` already declared them. Confirmed rather than assumed:
after `yarn build:native`, `coldCacheStats()` exposes both keys and the
whole suite is green. `metrics-trace.ts` is byte-identical to
`origin/main` and this branch touches neither `crates/` nor that
constant, so CI — which builds native fresh — never saw it.

Every new guard was checked by reverting the fix it protects. Two
initially passed and shouldn't have — one exercised an unmount/remount,
which re-runs `useState`'s initializer and so never hit the
live-component path the bug lives on; the other rendered a page whose
default filter emits no timestamp at all. Both were rewritten until the
mutation failed them.

## Known gaps — deliberately not fixed here

- **Phase 0 GPU-watchdog A/B was a DID-NOT-REPRODUCE, not a clean bill
of health.** 240s, neither arm provoked `mlx#3267`. Untested
aggravators: dragging the window mid-decode, an external display, a
Mission Control switch. The `ChildTransport` seam is kept so INFERENCE
can move to a fully separate OS process as a config change.
- **Signing is unexercised end-to-end** — needs a Developer ID
Application cert and 5 repo secrets. `dry_run` builds and signs without
notarizing.
- **Metrics still costs ~170ms to render**, now purely recharts mount
cost — with the cache hit, React builds all six chart trees in one
commit before it can paint anything. Fixing it means deferring chart
mount by a frame, which trades a blank window for a two-stage paint.
- **The "Model usage share" legend overflows its card by 149px** with 18
models. Recharts sizes a vertical legend `absolute`, so the card never
grows.
- The local-models table is auto-layout, so its columns still shift
slightly on swap; Sessions is `table-fixed` and does not.
- E2E smoke steps 3 and 6 (start the server from the tray; block ADMIN
3s) need Accessibility permission for `osascript` and have not been run.

Out of v1 scope: in-app chat, the `mlx agent` workspace, the
convert/quantize lab.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01WPjdT9SZ11PS93qqoxxHvY

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Changes authentication, non-loopback bind gating, and health
disclosure on the inference server—security-sensitive paths—alongside a
new signing/notarization release pipeline; risk is partly offset by
extensive new tests.
> 
> **Overview**
> **Centralizes inference hosting** in `@mlx-node/server/host`
(discovery, swap, engine env policy, logging, temp-root sweep) so **`mlx
serve`**, **`mlx launch claude`**, and the desktop sidecar share the
same `createInferenceHost` path. Addon-free subpaths `host/paths` and
`host/env-policy` are exported for callers that must not dlopen the
native addon.
> 
> **Hardens the HTTP server** for supervised use: bearer / `x-api-key`
at one choke point (with CORS default flip when auth is on), **minimal
unauthenticated `/health`** vs full body when authed, real readiness via
`deriveHealthStatus`, **bounded idempotent `close()`** that aborts
in-flight SSE, and **`runGuardedModelLoad`** ordering (drain suspension
outside the writer lock). Launch-claude wiring pins launcher policy
(`MLX_PAGED_PREFILL_CHUNK_SIZE=2048`) and fixes child env (drop
inherited `ANTHROPIC_API_KEY`, forward per-launch token).
> 
> **Docs/CLI**: documents **`mlx serve`**; retires **`mlx dashboard`**
in favor of the desktop Control Panel (`app://` + MessagePort). **CI**
runs `yarn build:ts` before early `yarn mlx` steps. **New
`desktop-release.yml`** builds fresh on macOS, validates manifest vs
tag, packages/signs, pre-notarization bundle verify, notarizes app +
DMG, uploads release artifact, optional Homebrew cask bump.
> 
> Large new test suites lock auth, health, host lifecycle, logger
redaction, and addon-free imports.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
f16d21b. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
## Summary

- recover canonical Gemma 4 tool calls when the model emits a valid
nested restart inside a malformed outer tool block, while preserving raw
output for diagnostics
- attach standalone local image paths pasted into the interactive TUI as
guarded `ImageContent`
- make image-bearing paged-cache identity durable with a versioned
SHA-256 payload digest, full 256-bit block keys, and explicit
key-layout/preprocessing markers
- persist and exactly restore Gemma 4 sliding-window image sidecars
after process restart, then skip the vision tower when the cached prefix
covers the complete image span
- advertise image support from valid Gemma/Qwen vision metadata during
model discovery while keeping the loaded native session authoritative
- expose Gemma 4 thinking with its real minimal/high level map and
support selectable thinking, canonical tool schemas, calls, responses,
and structured errors in template-less checkpoints
- seed the Gemma output parser when a post-tool prompt already opened
the thought channel so truncated reasoning never leaks into visible text
- keep audio and mixed-media cold recovery disabled and fail closed on
partial, misaligned, changed, reordered, or corrupt media state

## Root cause

Gemma 4 could sample a malformed outer tool block followed by a valid
nested `call:...` restart. The parser treated every byte before the
first argument brace as the tool name, causing dispatch of the malformed
prefix instead of the intended tool.

Pi's clipboard flow stores a pasted image in a temporary file and
inserts only its path into the editor. That path reached Gemma as plain
text because no input transform upgraded it to an image attachment.

The cold tier could persist image-aware global KV blocks, but Gemma 4
skipped sliding-window sidecar capture for media turns. After restart,
global layers could hit SSD while the out-of-pool sliding layers had no
faithful state. Replaying expanded image placeholder token IDs cannot
reconstruct vision embeddings, so image prefixes previously had to fall
back cold.

Agent discovery also hard-coded local models as text-only and marked
Gemma as non-reasoning. Template-less E2B checkpoints lacked
selectable-thinking and tool-schema rendering. After a tool result, the
canonical Gemma prompt continues inside an already-open thought channel;
initializing the parser in ordinary message state exposed that reasoning
as visible text.

## Impact

Malformed Gemma restarts now dispatch the intended tool, including
markers split across streamed chunks. Standalone absolute image paths
from the interactive TUI become image content only after extension,
magic-byte, size, and duplication guards pass.

A repeated Gemma 4 image prompt can reopen native SSD KV state after
process restart. The caller still supplies the raw image so mlx-node can
verify its digest, preprocessing identity, placeholder expansion, and
positions before accepting the cache entry. Missing or malformed vision
metadata, changed image bytes/order, incomplete sidecars, and corruption
remain cache misses.

`mlx agent --list-models` now reports thinking and image support for
capable Gemma checkpoints before weight loading. Template-less sessions
can select thinking, call tools with real schemas, consume canonical
tool responses, and keep pre-tool and post-tool reasoning separate from
the final answer.

## Cache accounting

A cache hit is capped at `prompt_tokens - 1` because the final prompt
token must be evaluated to produce next-token logits, then rounded down
to the 16-token block boundary. Therefore a 786-token prompt reports 784
cached tokens. The real restart trace reported 960 cached out of 961
prompt tokens.

## Validation

Combined PR #106 branch after cherry-picking the two PR #107 commits:

- both transferred commits have patch IDs identical to their PR #107
source commits
- parser integration review found the exact union of both PRs' tests: 40
unique tests, none lost or duplicated
- `cargo test -p mlx-core --lib gemma4` — 420 passed, 9 ignored
- targeted agent model/local-image/run-agent suites — 41 passed
- `cargo fmt --all -- --check`
- `git diff --check`
- `yarn typecheck`
- `yarn lint` — passed with pre-existing warnings only
- native arm64 addon rebuilt successfully in the combined worktree

Source-patch validation before transfer:

- focused Gemma manual/tool/parser/seeded-truncation tests — 63 passed
- focused agent discovery/config/stream tests — 64 passed
- image cache identity tests — 10 passed
- vision feature cache tests — 13 passed
- cold cache reopen integration test — passed
- process-restart gates — 3 passed
- real release-addon `mlx agent --trace` image + Bash task across
separate writer and restarted reader processes:
  - image OCR and the real Bash call both succeeded
- sessions recorded high thinking, separate thinking parts, one parsed
Bash tool call, and its real result
  - restarted reader reported `cacheRead: 960` for a 961-token prompt
- native trace recorded `cold_restore_walk` for 60 blocks,
`state=cold_sidecar`, 960 primed tokens, zero replay tokens, and
`vlm_vision_tower_skip`

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **High Risk**
> Touches durable KV/sliding cache identity, multimodal prefix restore,
Gemma tool/wire-format rendering, and session replay semantics;
regressions could cause wrong cache hits, broken image sessions, or
mis-routed tools/reasoning.
> 
> **Overview**
> This PR hardens **multimodal cold-cache identity** and **Gemma 4
session behavior** so image prefixes, tools, and thinking replay
correctly across restarts and agent flows.
> 
> **Paged / image cache (Rust):** Image-bearing block keys move from
`u64` hashes to **versioned SHA-256 payload digests**, with all four
digest words plus placeholder position wired into per-block
`extra_keys`, plus layout and preprocessing semantics markers. Hot
lineage still uses a compact combined key; durable keys bind the full
identity. Qwen vision cache keys follow the same digest type.
> 
> **Gemma 4 model:** Pure-image turns can **capture and restore
sliding-window cold sidecars** only after global K/V finalize succeeds
and only at checkpoints **at or after the full image span**; restored
sidecars must **exactly** match the effective prefix (no partial install
inside an image run). When the cached prefix covers the image span, the
**vision tower is skipped**. Template-less rendering gains
**`<|think|>`**, canonical **tool declarations**, in-turn **tool
responses**, and tool-result deltas that resolve the **function name**
from committed history (not opaque call ids). Prompt rendering records
whether output **starts inside an open thought channel** so sync/stream
parsers and promotion treat truncated post-tool reasoning as reasoning,
not visible text.
> 
> **Gemma 4 output parser:** Supports **prompt-seeded open channels**
and **recovers nested `call:` restarts** inside malformed outer tool
bodies (stream + offline).
> 
> **Agent / TS:** Tests document **media-held `sendToolResult` replay**
carrying `reasoningContent` / `thinkingEnabled` per historical turn vs
current `reasoningEffort`, plus a **local standalone image path** input
extension (guards, races, size caps). New integration tests assert
image-aware KV + sliding objects survive cold-cache **reopen** and
optional **OS process restart** with trace gates.
> 
> **Docs:** `paged-cache.md` describes the new image key ABI and
stricter image sidecar semantics vs text-only optimization.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
da91abc. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Brooooooklyn and others added 14 commits November 12, 2026 23:58
Stage S11 of the Splash int8 KV alignment (stack #344). Base: S37
(#373).

> **Read first: the windows grow a lot.** The plan margin follows Splash
now: `max(1 GiB, 2%)` instead of 15% + 1 GiB. On a 27 GiB M3 Pro, the
27B int8 + DFlash2 window goes from 98,297 to 221,177 tokens. No unit
test can show that this runs without swap; the live gate L13 must.

Qwen3.5 dense and MoE memory now goes through one process ledger, as in
Splash (`MemoryLedger`, `MemoryGovernor`). Every place that allocates
takes a claim first. A refused claim frees units in Splash order. If
that is not enough, the claim waits, yields its lane or fails. Splash:
`Engine::prepare`, `growLane`, `judge`, `suspendLane`, `admit`,
`MemoryGovernor::controlPass`.

```
before (S10f):
  scheduled row ──► step ──► blocked ──► engine::reclaim L1 → L2 → L3 (in order) ──► retry or fail
  serial turn   ──► grow pool ──► reclaim_kv on refusal ──► fail
  margin 15% + 1 GiB · no host rule · Metal OOM ends the drive loop

after:
  any allocation ──► claim (Floor / Start / InService / Optional / Host)
                       │
                       ▼
                 ledger.free: units in Splash order
                 FreeNow → Rebuild → NeedsWrite → InUse → LaneStart
                       │
           met ◄───────┴───────► short ──► judge
            │                               ├─ Wait  (≤ 30 s, then resource_timeout)
            ▼                               ├─ Yield (suspend lane, resume to its KV target)
           run                              └─ Fail  (capacity_exhausted)
  host rule + 500 ms control pass · margin max(1 GiB, 2%) · Metal OOM fails the rows and resets caches
```

## Changes
- New module `engine/governor/`: `ledger` (rule, rights, order, holds,
accounts), `host` (Splash `HostRule`), `governor` (charged,
`try_reserve`, MLX limit, start gate), `allocate` (the allocate loop and
judge), `wait` (`ResourceWait`, 30 s deadline), `monitor` (500 ms
pressure poll), `oom`, `metrics`, `status`.
- Scheduled lanes: `drive_once` is split into `prepare_step` and
`finish_step`. Each planned row takes its InService claim before the
step, in plan order (Splash `Engine::prepare`). A prefill row claims up
to `token_start + num_tokens` (Splash `workEndOf`). Draft-state growth
is a bytes claim under the same request.
- Judge and yield order follow Splash (`judge`, `laneToYield`,
`yieldsBefore`). A yielded lane keeps its KV target. It resumes only
when its retry time has come and the scheduler is not draining.
- Admission: a Start or InService claim reserves the GDN cell. A lone
Start may drop its own kept chain once (Splash `droppedLease`). A
scheduled prepare leaves its refusal to the scheduler, which defers it.
- Serial lane: each paged step runs in a whole-turn claim. A
host-refused AR or DFlash2 decode step vacates its lane, waits in place
and replays its tail. Greedy output stays exact.
- Speculative lookahead (MTP and DFlash2, dense and MoE) is an Immediate
claim. A refusal decodes the turn AR, with no wait.
- Queued chains (Splash `Cache::setWantedChains`) and the resume point
(`StateCache::resumePoint`) are kept from Start claims.
- Host: a 500 ms control pass on each model thread, also when idle. The
start gate retries host and driver refusals for 30 s (Splash
`StartupRetryWindow`), outside the pool-growth lock.
- Publications (replay point, ladder rungs, history) are claims. A
refused Optional publication is dropped and counted.
- Margin: the qwen3_5 plan uses `max(1 GiB, 2%)`. Other families keep
15% + 1 GiB (`Margin::Unguarded`).
- GPU OOM: a command-time Metal OOM fails the model's running and queued
rows and resets its caches. The model thread lives on.
- Errors: `resource_timeout`, `capacity_exhausted` and
`metal_out_of_memory` map to 503 in `/v1/messages` and `/v1/responses`
(Anthropic `overloaded_error`, Retry-After 1).
- Status: `memoryGovernorStatus()` (napi) and `/health`
`memory_governor` (authenticated body only): accounts, charged, claims,
owed, resource waits, TTFT parts (Splash `holderOf`), decode-gap causes,
counters.

## With stops (S30) and the deferred GDN fold (S14)
- A stopped running row ends in its step (its prefill row vacates, its
decode row commits what it generated): the ledger's cancel reap skips
it, and a stopped row is planned and granted without a claim even while
its wait has not reached its retry (Splash `Engine::stop` → `settle` →
`finish(Stop)`).
- A suspended request's end (cancel or stop) signals progress, so waits
retry at once (Splash `Engine::release`: a lane or a suspended request
gives its memory back).
- A stop during the serial lane's wait (suspend wait, or a refused
step's wait) vacates the lane if it is not yet and completes on what the
turn generated (done "stop"); a cancel stays the cancel error. AR and
DFlash2 (`run_paged_turn`, `run_paged_dspark_turn`).
- A cancel or stop on a suspended (preempted) scheduled turn settles in
the pass's reap, not when the turn is next first in line (Splash
`Engine::settle` ends a request that is not in flight at once).
- A cancelled or stopped turn's wait no longer times out: the scheduler
marks its wait finalized (Splash `Engine::deferEnd` keeps the first
end), and the serial waits check the cancel before the 30 s limit. A
stop never comes back as `resource_timeout` (503).
- A running turn stopped right after its last prefill slice sampled its
first token ends "stop" with 1 token (Splash `generatedTokens` counts
that token), not the cancel error.
- A stopped turn whose prefill slice fails with a Metal OOM keeps the
failure, so the GPU OOM recovery still runs (Splash restarts on
`metal_out_of_memory` however the request ended).
- A DFlash2 lane replayed after a suspend packs fresh cells from the
replayed caches; the old cells' pending rows go (the replay fed their
tokens).
- The pending GDN tape is in the lane transient, which the ledger
reserves as the model's untracked bytes. Large windows are priced by the
prefill arm, so the windows below do not move.

## Memory plan
The new margin moves the planned windows (load-plan tests, M3 Pro 27 GiB
working set):

| plan | before | after |
|---|---|---|
| 27B int8 + DFlash2 window | 98,297 | 221,177 |
| 27B bf16 window | 50,041 | 112,473 |
| serial MTP window | 57,337 | 155,641 |

Margin on this working set (28,991,029,248 B): 2% is 579,820,584 B,
below 1 GiB, so the margin is 1,073,741,824 B (was 15% + 1 GiB =
5,422,396,211 B). The window grows by the freed 4.0 GiB of KV.

## Deleted
- `engine::reclaim` and the in-order L1-L3 reclaim paths: `KvNeed`,
`KvReclaim`, `DraftReclaim`, `SchedReclaim`, `StepNeed`, `DraftUnits`,
`reclaim_for_blocked_step`, `try_grow_pool_by`, `reclaim_keep`,
`ModelReclaim`, `retry_after_reclaim`.
- `grow_paged_pool_for_prompt`, `ensure_paged_pool_for_prompt`,
`ensure_paged_pool_keeping`, `free_for_kv`, `free_for_draft`.
- `DraftRefusal`, `refuse_draft`, `take_draft_refusals`, `kv_need_met`,
`last_grow_room`.
- `MLX_SCHED_RESERVE_FULL_ISL` (code, test comment, docs row).
- Still read by Legacy families, so kept: `handle_blocked_alone`,
`reclaim_one_idle_scheduled_with`, `try_grow_reservation_pool`,
`draft_shortfall` (qwen4_exp and the other non-ledger families).

## Tests
- 100 named mutations (96 Rust, 4 TS). Each test is green with its
switch off and red with its named mutation on. One test build per part,
`RUST_TEST_THREADS=1`. The list is in `MUTATIONS.md`, `rf-mut.txt`,
`rb-mut.txt`, `rb-fix-mut.txt`, `cx1-mut.txt`, `r2-mut.txt`,
`r3-mut.txt` and `MUTATIONS.md` round 4. Examples:
- ledger: Splash rights table (R1), take order (O1), holds (H1, H2),
unsized credit = charged drop (U2), accounts sum to charged (A1);
- host and waits: host rule (W1-W3), 30 s deadline restarts only for
earlier lanes (T2, T2b), host-refused waiting (R2, HW1);
- scheduled lanes: yield order (Y1), one refused row does not stall the
wave (P2m), judge (J1), resume to the target (V1, V2), droppedLease
(D2), laneToYield before both branches (F8), cancelled refused lane ends
(RC1), vacated lane drops its cell (CL1);
- serial lane: vacate and wait in place (Y2), replay matches the solo
tokens, AR and DFlash2 (Y3), lookahead refusal decodes AR (LA1, LA2);
- start gate outside the growth lock (SR1, SR2); GPU OOM text and reset
(O2, K4, K5); TTFT and decode-gap causes (Z1, Z2, TW1); status reads
while a turn runs (Z3);
- TS: `resource_timeout` and `metal_out_of_memory` → 503 (TS1, TS4),
`capacity_exhausted` is not a context error (TS2), `memory_governor`
only in the authenticated `/health` (TS3).
- with S30 / S14: a stopped running row ends in its step (RS1, RS2), a
suspended request's end wakes the waits (SP1), a stop in the serial
suspend wait completes (VS1), a replayed DFlash2 lane drops its pending
GDN rows (AP3), a stopped suspended turn settles in the reap (PS1), a
stopped turn's expired wait ends "stop", not `resource_timeout` (FS1
scheduled, SW1 serial), a stop at the first sampled token ends "stop"
(FT1), a stopped slice keeps its GPU OOM (OS1).
- review fix: a decode row claims only the rows it writes (`num_tokens`
+ its draft allowance, Splash `Engine::workEndOf`): at a block boundary
(31 rows written + 1 pending, 16-token blocks, no budget to grow) the
row is granted (DC1,
`a_decode_row_at_a_block_boundary_claims_only_its_rows`).
  - review fixes (verified findings):
- `try_reserve` and the start gate sample again when a reservation
retired between the sample and the lock (Splash
`MemoryGovernor::tryReserve` reads charged and reserved at one instant):
another model's 80 bytes landing in that window refuse a second 80 under
a 100-byte limit (E1m,
`a_reservation_retired_after_the_sample_is_still_charged`);
- the host pass's settle deadline is per model (Splash runs one engine
per governor): an empty model passing first each tick no longer starves
a 2 GiB model's reclaim (E3m,
`an_empty_model_does_not_spend_another_models_host_pass`);
- a DFlash2 verify lends its lane (both GDN cells, pending rows, draft
window) to the target across its claim, so a suspend's vacate drops it
before the wait (Splash `Runtime::suspend` →
`QwenStateStorage::releaseLane`), dense and MoE (R1m,
`a_suspended_dflash2_lane_drops_its_cells_and_window`,
`moe_suspended_dflash2_lane_drops_its_cells_and_window`);
- a take that removed its unit is Met though it measured nothing (Splash
`Cache::take`), so the ledger lists again and the state that shares the
block is taken (R2m,
`a_take_that_frees_nothing_measurable_lists_again`).
  - review fixes, round 2:
- a decode row whose pending token ends the turn (EOS, `max_new_tokens`,
repetition cutoff) claims nothing, so a finished request is never
refused, suspended or failed `capacity_exhausted` for a row it never
writes (Splash `Engine::commit` ends the lane at that token) (TB1,
`a_terminal_decode_row_claims_nothing`);
- an MTP lane claims its draft state: the admission reserves the GDN
cell plus the draft state's fixed part (Splash
`CompositeStateLayout::laneBytes` under the start claim), and every row,
prefill slices included, claims its draft K/V growth (Splash
`Engine::growLane`) (MB1, `a_speculative_start_claims_its_draft_state`;
MP1, `an_mtp_prefill_slice_claims_its_draft_growth`);
- MTP's AR step (Step A, after a refused lookahead) runs under
`paged_step_claimed`, dense and MoE: a refused growth waits in place up
to 30 s instead of failing `context_length_exceeded` (MA1,
`mtp_ar_step_waits_for_its_growth`);
- a whole qwen3_5 turn's GPU OOM is classified at its boundary
(`run_paged_turn`, `run_multimodal_turn`, dense and MoE), as Splash
`NativeRuntime::executionFailed` does: an OOM MLX reports outside every
claim (a DFlash2 verify at the accept's wait, a serial AR sample) fails
the turn `metal_out_of_memory:` and arms the model reset (WO1,
`a_verify_oom_outside_the_claim_arms_recovery`).
  - review fixes, round 3:
- a bytes need the host did not refuse takes the pool's dead leaves and
cuts the extent they empty (Splash `Cache::takeReclaim`:
`releaseExtent`, then `evictOne` + `releaseExtent`, one extent per take,
`Phase::DeadLeaves` before ordinary states). New unit
`UnitKey::DeadLeaves` (FreeNow, stamp 0, after `Extent`); the claim's
prompt chain and, without certain reuse, the queued chains are kept
(Splash `Walk::reused` / `Walk::restored`). A critical host pass on a
pool of cached chains with no empty extent now cuts it (R3,
`critical_host_pass_evicts_dead_leaves_to_cut_an_extent`);
- a stop during a suspended serial lane's replay completes the turn
"cancelled" on its generated tokens instead of erroring the stream
`prefill cancelled` (Splash `Engine::stop` settles a suspended lane in
any phase); the wait also checks cancel after its sleep and control pass
(R4, `a_stop_during_the_replay_completes`, AR and DFlash2);
- one row's GPU OOM fails every turn its step completed, vacated stops
included, before any of them finishes (Splash restarts on
`metal_out_of_memory` however the request ended) (E4,
`one_rows_oom_fails_the_peer_its_step_completed`).
  - review fixes, round 4:
- a scheduled lane's prefix preparation (GDN replay of a cached prefix,
at admission and at a suspended lane's resume) that MLX fails for Metal
memory, its own command or an earlier one's late error, now fails the
request `metal_out_of_memory:` and restarts the model at once, before
the next step: resident lanes fail, idle owners, the ladder, the prefix
cache and the DFlash2 store reset (Splash
`NativeRuntime::executionFailed` wraps `Engine::tick`, admission
included) (E7, E7b, `a_prefix_preparation_oom_restarts_the_model`).
- Final gates on the rebased commit (625a2b201, on S30 3a56a8e):

| gate | result |
|---|---|
| `cargo fmt --all -- --check` | clean |
| `cargo clippy --workspace --all-targets -- -D warnings` | clean |
| `cargo test -p mlx-paged-attn` (16 binaries + doctests) | 333 passed,
0 failed, 13 ignored |
| mlx-core `--lib` (`RUST_TEST_THREADS=1`) | 4,734 passed, 0 failed, 220
ignored |
| `yarn build:native` | ok; `index.d.cts` copied, no change |
| `yarn typecheck` and `yarn tsc -b --force` | ok |
| `vp lint --type-aware --type-check`, `vp fmt --check` (10 touched TS
files) | clean |
| `vp test __test__/server packages/server packages/lm/__test__` | 1,578
passed, 7 skipped |
| `git grep MLX_MUT` | 0 |

- Re-pinned numbers: none. The memory plan windows (221,177 / 112,473 /
155,641) are unchanged by the rebase: S14's pending GDN tape enters only
the decode arm of the lane cost, and these windows are priced by the
prefill arm.

- After the rebase onto S37 (`69c404045`): `cargo fmt --check`, `cargo
clippy --workspace --all-targets -D warnings`, `yarn build:native` (no
`index.d.cts` change), `yarn typecheck`, `tsc -b --force` clean;
mlx-core `--lib` (`RUST_TEST_THREADS=1`) 4,743 passed, 0 failed; `vp
test` server, lm and desktop: 2,125 passed, 7 skipped.

- Round 2 fixes (08048a1): `cargo fmt --check`, `cargo clippy
--workspace --all-targets -D warnings` clean; scoped mlx-core `--lib`
(`RUST_TEST_THREADS=1`): `engine::` 549, `models::qwen3_5` (with MoE)
565, `models::qwen4_exp` 242, `models::qwen3::` 46, `cold_tier::` 38,
all passed, 0 failed; no `#[napi]` file changed; `git grep MLX_MUT` 0.

- Round 3 fixes: `cargo fmt --check`, `cargo clippy --workspace
--all-targets -D warnings` clean; `cargo test -p mlx-paged-attn --lib
block_allocator` 65 passed; scoped mlx-core `--lib`
(`RUST_TEST_THREADS=1`): `engine::` 550, `models::qwen3_5` (with MoE)
567, `models::qwen4_exp` 242, `models::qwen3::` 46, `cold_tier::` 38,
`transformer::paged_kv_cache_adapter` 186, all passed, 0 failed; no
`#[napi]` file changed; `git grep MLX_MUT` 0.

- Round 4 fix (E7): `cargo fmt --check`, `cargo clippy --workspace
--all-targets -D warnings` clean; scoped mlx-core `--lib`
(`RUST_TEST_THREADS=1`): `engine::` 551, `models::qwen3_5` (with MoE)
567, `models::qwen4_exp` 242, `models::qwen3::` 46, `cold_tier::` 38,
all passed, 0 failed; no `#[napi]` file changed; `git grep MLX_MUT` 0.

## Gaps
- No claim is ever Pending yet: `Returning` is zero until the SSD state
tier lands (S13), so holds never engage in production.
- Only our own allocation points are claimed. MLX transients inside eval
are a plan reserve, not claims.
- One process ledger. Units are taken on the caller's model thread, so
another model may change room in between. Each model's control pass has
its own 1 s settle, so in one second each loaded model's pass may take
up to M (Splash's one engine takes it once).
- A suspended DFlash2 lane's buffers are dropped, not pooled: the replay
allocates a fresh lane (Splash `activate` takes the pooled buffers
back).
- The serial suspend covers AR and DFlash2 decode steps only. A
host-refused serial prefill chunk or MTP step waits in place, up to 30
s. Vision turns never suspend.
- A refused DFlash2 cycle lookahead decodes that cycle AR (shared
driver), where Splash judges the verify rows.
- An MTP lane's draft fixed part is reserved at admission and held only
to the turn's first forward. mlx-node allocates the verify-time parts
(recurrent snapshots, tapes, hidden rows) at the first verify, and from
then on they count through `charged`; Splash allocates the lane's
buffers inside the start claim. A cached-prefix MTP turn, which then
declines MTP, over-reserves that part until its first forward.
- A turn's finalization (`finish_completed` → `save_paged_history` → GDN
checkpoint) is not checked for GPU OOM. Not fixed: no GPU command is
committed between a step's last wait and `finish_completed` (a decode
wave waits on its sampled tokens, a prefill slice ends in
`synchronize`), and the finalization only evaluates views and clones
handles. So a failed command's error is raised in the step that ran it,
where `note_gpu_oom` sees it, and that step's OOM fails every turn it
completed (E4). Only an error MLX reports in a later step stays gap 10.
Only a fresh allocation for the finishing request itself could fail
there, and that writes nothing a peer reads. A whole turn's finalization
is covered by the turn boundary above.
- Dead leaves for a bytes need (R3) differ from Splash's walk in four
ways. (1) They are one unit at stamp 0, so they go before the ladder
rungs too (Splash takes `Phase::Checkpoints` first). (2) Kept and queued
chains are matched by tokens, salt and image keys ignored, so a
same-token chain on another salt is kept too. (3) The unit's size counts
the blocks a state still marks (they free once the state goes, which the
ledger lists next); the bound over-counts by the chains of states the
claim may not take. (4) A kept block above the cut stops the cut there,
though moving it down would let it go lower. A KV need with blocks takes
dead leaves in place (`allocate`), not through this unit.
- `skip_cache` has no trigger: qwen3_5 restores cold chains
synchronously, and a restore the pool refuses is already a start without
the cache.
- Accounts are published between drive passes, so a whole turn's live
state reads as `fixed` until it ends.
- No request priority; the live GDN unit cap stays 2 (S15); the pressure
monitor polls every 500 ms.
- Other families keep their margin and allocate outside the ledger. They
see it only through `set_memory_limit`.
- The full list (25 rows) is in `S11-design.md` §16.

- A GPU OOM that MLX first reports inside `synchronize` is swallowed by
the shared `mlx_synchronize` shim (it only prints `[MLX] Exception in
synchronize`), so the ledger never sees it: no row fails and no cache
reset runs. Changing that shim touches every family.
- A recovered GPU OOM still writes a `native_error` trace line, so the
desktop supervisor's older `lying` detector marks the sidecar `lying`
until it restarts (a false alarm).
- A turn that waits for a memory claim (up to 30 s) is already in S37's
turn journal. Splash journals a turn only once it is admitted
(`Engine::completeAdmission`), so a crash on another lane during that
wait can count against the waiting request (S37 gap 13).

## Not in this PR (live, not run)
- L0: full-profile build, one AR turn, the "memory plan" log line with
the new margin and window.
- L13a: 15 min three-worker churn on scheduled lanes
(`MLX_CONTINUOUS_BATCHING=1`, `--max-memory 22G`): G4 gap (max ≤ 10 s,
p99 ≤ 5 s), G8 no failure but context, G9 accounts sum to charged and
owed = 0, First token, Churn.
- L13b: the same on the serial lane (suspend and replay).
- L13c: L13a on S10f, as the before row.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
…375)

Stage S33 of the Splash int8 KV alignment (stack #344). Base: S11
(#374).

Qwen3.5 dense and MoE now cut a prefill that runs beside a decoding
lane. The cut is the rows the last timed unit says fit in 500 ms, so a
decoding lane waits about 500 ms at most behind a prefill. Splash:
`Scheduler::planPrefill`, `cutRows`, `leadsBefore`, decode debt,
`prefillAdmissionOrder`. Every other family keeps the fixed 2048-row
budget and plans exactly as before.

```
before:  one step = decode rows + prefill rows from ONE 2048-token budget (MLX_SCHED_MAX_BATCHED_TOKENS)
         a decoder beside a long prompt waits for a whole 2048-row prefill row every step
         leader = FCFS; admission = FCFS; no prefill timing

after:   one step = decode rows (outside the unit) + one prefill unit (leader + up to 3 joiners)
         no decoder  -> unit 2048 rows
         a decoder   -> unit = cut_rows(leader): 512 until a unit is timed, then
                        clamp(R_last * 500 ms / T_last * deeper, 512, 2048); a rest < 512 rides along
         after a contended unit the decoders are owed 0.5 x its wall (decode-only steps)
         leader = overdue (3 overtakes) oldest, then fewest remaining, then order
         a start is admitted only when the next unit serves it
```

## Changes
- `engine::scheduler`: `PrefillUnit::{Fixed, Measured}`. `Fixed { budget
}` is the old loop. `Measured` ports `cutRows`, `leadsBefore` with
`MAX_OVERTAKES` 3, the joiner rule `(remaining − 1) % 2048 + 1` (skipped
when it does not fit), at most 4 lanes (`PREFILL_MAX_LANES`), and the
attention-pair bound `dense_attention_pairs(native − 2048, 2048)` (the
leader halves down to 64 rows while above it). Cancelled rows and S11
waiters whose retry is not due never lead and never size the unit.
- Measure: the step's prefill-phase wall, taken only when every planned
row ran timed. A failed or untimed row sizes nothing.
- Decode debt: a contended unit adds `decode_share × wall` to
`decode_debt_ms`; decode steps pay it down; it drops when no lane
decodes (Splash `dropStaleDecodeDebt`).
- `--decode-share <share>` on `mlx serve` and `mlx agent` → host →
loader → the qwen3_5 / MoE load option `decodeShare`. Parsed as Splash
`parse_decode_share` (finite, ≥ 0). Default 0.5. The loader refuses it
for other families.
- Admission (`hs`): a start waits until `serves_candidate` says the next
unit serves it. A live continuation counts the tokens it keeps. A held
start takes Splash `deferWait` + `deferAdmission`: its wait resets and
its ledger claim stops waiting. Held starts wait in their own queue in
submission order and hold back nothing (Splash `Engine::admitQueued`:
"The others wait for scheduling, and hold back nothing"), so a later
short start is admitted past a held long one. Only a start refused
memory or a lane holds back the starts after it. A held start keeps the
submission order it took when first held, and each prefill unit that
serves a later submission overtakes it (Splash `Scheduler::complete`),
so after 3 it is overdue, leads and is admitted. A later turn of a held
owner, a reset, a barrier or an exclusive command does not pass a held
start. Held starts are not retried while a lane is suspended (Splash
recovery tries no start of that priority).
- Executor: times its decode and prefill phases
(`StepResult.decode_wall_micros`, `prefill_wall_micros`). A prefill
claim ends at its row's end (`row_work_end`, Splash
`Engine::workEndOf`).
- One G: `DECODE_GAP_MS` (500) feeds the cut and S11's decode-gap
classifier. The prefill wall of a step reaches every decoding lane
beside it, so a gap over 500 ms there is counted as PrefillUnit
(`decode_gap_causes.prefill_ms`).
- Status: `memoryGovernorStatus().scheduler[]` and `/health`
`memory_governor.scheduler[]`, one entry per model with Splash's names:
`queued`, `waiting_resources`, `waiting_prefix`, `prefilling`,
`decoding` (by phase, as Splash `Scheduler::snapshot`),
`prefill_batches`, `prefill_rows`, `prefill_units`, `bound_cuts`,
`decode_batches`, `decode_batches_by_width`, `decode_gap_target_ms`,
`contended_prefill_ms` (Splash `FineLatencyHistogram`), `replans`. The
counters are atomics the model thread registers once; `/health` joins
the served model name.
- `LatencyHistogram` moved to `engine::latency` beside the new
`FineLatencyHistogram`.

## Deleted
- `MLX_SCHED_MAX_BATCHED_TOKENS`, `scheduler_max_batched_tokens`,
`Scheduler::max_num_batched_tokens`, `StepPlan::token_budget`, its docs
row. `git grep` finds none of them.
- `DECODE_GAP_SECONDS` and `PassWork::ran_prefill` (replaced by
`DECODE_GAP_MS` and the step's prefill wall).

## Plan numbers
No existing plan number moved: no assertion of an existing test changed,
and every `Fixed` scheduler test is unchanged. The new numbers below
come from the new tests.

| case | rows |
|---|---|
| no decoder, no measure | 2048 |
| a decoder, nothing timed yet | 512 |
| a decoder, last unit 2048 rows in 2048 ms at position 0, leader at
2048 | 512 (floor) |
| a decoder, last unit 2048 rows in 204.8 ms, leader at 2048 | 1667 |
| a decoder, 900 left, cut 512 | 900 (the rest rides) |
| 3 decoders with draft allowance 4, leader unmeasured | 512 (decode
rows outside the unit) |
| leader at 16,384, native window 8192 | 512 (pair bound) |
| debt after one 512 ms contended unit at share 0.5 | 256 ms, paid by 9
decode-only steps of 30 ms |

## Tests
- 37 new tests (35 Rust, 2 TS), 38 named mutation runs (`MUTATIONS.md`).
Each test is red under its mutation and green without it. Rust mutations
ran as runtime switches on one test binary; the TS ones by edit, then
reverted. All switches are gone (`git grep MLX_MUT` = 0).
- Plan: Q1 unit always 2048, Q3 `deeper` = 1, Q2 no rest rule, Q4
untimed rows timed, J1 joiner takes what is left, B1 decode rows charged
to the unit, L1 FCFS leader, O1 no overtake count, W1 no width break, P1
no halving, C1 cancelled lanes lead, E1 retry clock ignored, K1 a
refused lane is skipped in overtakes.
- Debt, counters, admission: S2 share 0, C2 every unit in the histogram,
H1 bucket = floor ms, A1 every candidate served, AW1 admitted waiters
left out of the candidate's plan, W3 a waiting lane counts as waiting
for resources.
- Held starts (`hs`): AQ1 a held start kept as a refused one (it blocks
the later short start), AQ2 held starts never overtaken, HR1 the retry
takes all held starts out first (a GPU OOM restart then misses the ones
not yet tried), HD1 a held start keeps its host refusal (it stays in the
host deficit).
- Wiring (`hs`): M1 the hook never applied, W2 prefill claim ends at the
pinned break, T1m prefill wall left 0, G2 the pass keeps no prefill
wall, S3 admission skips the gate, H1 kept tokens not counted, D3 a held
start keeps its wait, P1 the prepared start left out of the gauges, R1
the scheduler not registered, D2 the dense hook ignores the load's
share.
- Status and gaps: S1 one entry for all models, G1 the step's wall not
added to the lane.
- TS: D1 the parser accepts negatives (`__test__/cli/serve.test.ts`),
the health name join skipped (`__test__/server/health.test.ts`).
- Gates on the squashed head: `cargo fmt --all -- --check`, `cargo
clippy --workspace --all-targets -- -D warnings`, `yarn build:native` (+
`index.d.cts` copy, no diff), `yarn typecheck`, `yarn tsc -b --force`,
`vp lint --type-aware --type-check` and `vp fmt --check` on the touched
files: clean. mlx-core `--lib` (`RUST_TEST_THREADS=1`): 4,773 passed, 0
failed, 220 ignored. `vp test` (touched tests, `__test__/server`,
`packages/server`, `packages/lm/__test__`, `packages/cli/__test__`): 78
files, 1,865 passed, 8 skipped.
- After the rebase onto S11 d81f71b: S11's decode work end no longer
adds `+1` (the pending token is already in `num_tokens`), so
`row_work_end` follows it and `a_prefill_claim_ends_at_its_row_end` now
expects 21. fmt, clippy, `yarn build:native`, `yarn typecheck`, `yarn
tsc -b --force`: clean. mlx-core `--lib` (`RUST_TEST_THREADS=1`): 4,787
passed and 1 failed (that test, since fixed); `engine::` rerun: 581
passed, 0 failed.

- Review round r1 (held starts queue apart): `cargo fmt --all --
--check`, `cargo clippy --workspace --all-targets -- -D warnings`:
clean. mlx-core `--lib` (`RUST_TEST_THREADS=1`): `engine::` 583 passed,
`models::qwen3_5` (MoE included) 567 passed, `models::qwen3::` 46
passed, 0 failed. No `#[napi]` or TS file changed.
- Review round r2 (held starts stay visible to recovery and leave the
host deficit): the held retry takes each start from the queue only when
it tries it, so a GPU OOM restart fails the rest. A held start clears
its host refusal (Splash `Engine::deferWait`), since `sync_claims` never
visits it. fmt, clippy: clean. `engine::` 585 passed, `models::qwen3_5`
567 passed, `models::qwen3::` 46 passed, 0 failed.
- Review round r3 (a start admitted earlier in the same pass is a lane
to the next candidate): `serves_candidate` plans over the running lanes
plus the admitted `Waiting` turns not yet promoted (Splash
`Scheduler::admit` sets `Phase::Prefill` at once). Probe: a 40,000-token
start waiting for promotion now holds back a 50,000-token candidate and
still lets a 300-token one join. fmt, clippy: clean. `engine::` 586
passed, `models::qwen3_5` 567 passed, `models::qwen3::` 46 passed, 0
failed. No `#[napi]` or TS file changed.

## Gaps
- The unit is all prefill rows of one step, each its own forward after
the decode batch. Splash joins them in one command, so joiners here add
their forward's fixed cost. No stage owns a batched prefill forward.
- qwen4_exp (Flash Next) prefill is never cut; Splash runs
streamed-weight groups in layer passes.
- The admission-time GDN prime over a cached prefix, and the same prime
on a resume, run uncut between steps (S12 resumes at state boundaries).
- A cached prefix a start would hit only in the prefix cache counts as
uncached (no admission prefix probe), so such a start is admitted later
than in Splash.
- Each start is checked against the resident lanes and the starts
already admitted (Splash `Scheduler::admit` makes them Prefill lanes at
once), one candidate at a time in submission order; Splash plans all
candidates of a pass together and replans without the unserved ones, so
here a start admitted earlier in a pass is not re-checked when a later
one leads it (Splash would hold the earlier one).
- No priority tier, no Spill lanes or restoring starts in admission.
- `MLX_SCHED_LONG_PREFILL_TOKENS`, the pinned grid and
`MLX_PAGED_PREFILL_CHUNK_SIZE` stay for the other families; qwen3_5 does
not read the grid.
- Refused or blocked rows are left out of the sample; joiners already
planned still run (Splash replans the command).
- Share 0 gives one decode row and one unit per step; Splash alternates
whole commands.
- Status leaves out `waiting_mask`, `terminal`, pass and index-page
counters; `decode_batches_by_width` has one key per width up to
`max_num_seqs`.
- `prefill_units`, `prefill_batches` and `prefill_rows` count only units
with a timed row; Splash counts each committed command and each
completion, failed rows included.
- A step whose only prefill rows are cancelled, stopped or blocked still
has a prefill wall of a few µs, so a gap over 500 ms in that step reads
as PrefillUnit with about 0 ms (inherited from S11's classifier).
- No tiny Qwen3.5 forward exists, so `the_step_times_its_prefill_phase`
runs the real executor on the test model, and the `publish_gauges()`
call inside `drive` has no test of its own.

## Not in this PR (live, not run)
- L1: qwen3.8-27b, `MLX_CONTINUOUS_BATCHING=1`; A decodes while B sends
about 32K tokens. Pass: A's largest gap ≤ 1000 ms, A still decodes after
B's first token, `scheduler.bound_cuts` > 0. Before row on S11.
- L3: B alone, TTFT on S33 vs S11 (information).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
…it and on rolling checkpoints (#376)

Stage S12 of the Splash int8 KV alignment (stack #344). Base: S33
(#375).

A DFlash2 turn now plans and claims its states like Splash. It plans
rolling checkpoints, a junction at the KV hit and the replay point
(Splash `configureDraftStatePlan`). Each capture is a ledger claim
(Splash `Engine::stateClaim`). States are published after every prefill
chunk. A state is the GDN cell plus a 4-bit draft context window. The
live lane between turns is gone: the next turn resumes at the deepest
stored state.

```
before:  prime: live lane (seq 0 kept live) | store hit | cold; no junction
         prefill breaks: GDN ladder rungs + R; one publish after the prefill (abort drops it)
         state = GDN cell + bf16 draft K/V window; 3,072 MiB state budget, oldest first
         draft K/V = sliding buffer, +256-row regrowth
after:   lookup: deepest store state S; probe the whole KV hit K; J = K if a state sits below K
         plan: checkpoints 4096·k (disposable) + J (ordinary) + R (ordinary, in use)
         each chunk: book its KV (growLane), then claim its capture:
                                  R InService CanWait | checkpoint / J Optional Immediate
                                  refused + reclaimable checkpoint -> SettledOnce, from the lane
         publish after every chunk: register blocks, publish, retire the older checkpoint
         state = GDN cell + 4-bit window (5,898,240 B on the 27B); no budget, checkpoints go first
         end: register + release; ring + window -> idle lane; draft K/V = fixed 2,048-slot ring
```

## Changes
- `dflash2_state/plan.rs` (new): `planned_checkpoints`,
`replay_state_boundary`, `configure_draft_state_plan`,
`plan_draft_context` and `command_breaks` (Splash `reserveCaptures`
"passed" rule). The checkpoint margin is the constant
`PREFILL_STEP_SIZE` (Splash `prefillTokenBudget`).
- Store: `StateClass` (checkpoint / ordinary), dedup, upgrade on an
ordinary publication (keeps the publication, Splash `makeOrdinary`),
`use_state` / `end_use`, `checkpoint_state`, `state_below`, and lineage
bytes in each entry's size.
- Captures are claims: `state_claim` + `reserve_capture`, claimed after
the chunk's KV is booked (`book_chunk`, Splash `Engine::prepare`:
`growLane` before `reserveCaptures`), so an optional state is refused
instead of taking the room the chunk needs. A refused checkpoint with a
reclaimable checkpoint on the lane retries as `SettledOnce` and
snapshots inside the claim (`Reached::FromLane`, Splash `fromLane`). A
refused capture still runs use, dedup and retire.
- The restore is a claim too: GDN cell, plus the ring bytes the idle
ring lacks, plus a window only when the draft is rebuilt and the idle
lane has none (Splash `admitIdleLane`). Wait retries; Fail makes the
turn cold (Splash `admit`).
- `register_committed_blocks` registers a chunk's full blocks before its
states are published, so a cancelled prefill keeps what earlier chunks
published.
- 4-bit draft context window: Metal store, load and copy
(`draft_context.metal.inc`, `mlx_draft_context.cpp`),
`DraftContextWindow`. Rows are cast to bf16 before the store. A restore
dequantizes and projects the window, and skips it when the first point
is a full window past the resume (Splash `restoresDraftState`).
- Resume: junction probe over the whole KV hit, `lazy_junctions` counted
once per admission (Splash `recordLookup`), plan and restore decision at
resolve. A turn without cache reuse keeps its turn state with an empty
plan.
- DFlash2 finalize registers, releases, then ends the replay-point use.
`save_paged_history` skips the frontier check on a released lane, so the
GDN dirty latch stays clear.
- AR turns read GDN from a store entry (in use, restamped at the end).
- Unit order: a model's checkpoints go first, then the stamp merge of
ordinary states and idle owners (Splash `Cache::nextUnit`
`Phase::Checkpoints`).
- Draft K/V is a fixed ring of 2,048 slots plus the block rows, with a
per-row mask in eager and compiled paths. The ring and window live in an
idle lane between turns. Aborts and a dropped stepper also put them
back. The idle lane counts in the states account.
- Serial-lane suspend: a DFlash2 prefill or verify that yields vacates,
waits, then claims the lane buffers, then the KV, and replays from its
deepest state (Splash `admit` order). A vacate publishes nothing.
- Counters in `memoryGovernorStatus().dflash2States` and `/health`
`dflash2_states` (Splash keys).

## Memory plan

| plan | before | after |
|---|---|---|
| 27B draft K/V ring (`kv_ring_bytes`) | 47,329,280 (2,311 rows) |
42,106,880 (2,056 rows) |
| 27B lane beyond the pool cell | 201,273,344 | 201,949,184 (ring +
5,898,240 window) |
| 27B lane vs Splash `laneBytes` | 905,216 short | 229,376 short (conv
alignment −393,216, ring rows +163,840) |
| M3 Pro 27B int8 + DFlash2 pool blocks | 14,137 | 14,136 |
| M3 Pro 27B int8 + DFlash2 window | 221,177 | 221,177 |
| M3 Pro 27B bf16 + DFlash2 window | 112,473 | 112,473 |
| M3 Pro 27B serial MTP window | 155,641 | 155,641 |
| 27B state (GDN cell + window) | – | 159,842,304 + lineage bytes |

## Deleted
- `MLX_DFLASH2_STATE_BUDGET_MB` and the state budget
(`STATE_BUDGET_ENV`, `DEFAULT_STATE_BUDGET_MB`, `parse_state_budget`,
`with_state_budget`, `trim_to_budget`).
- `DFlash2States.unregistered`, `drop_unregistered`,
`settle_replay_state`, `publish_replay_state`, `replay_capture_row`,
`draft_keep_from`.
- The live lane: `DFlash2Hit::Live`, `reusable_paged_dflash2_prefix`,
`StoreHit::beats_live`, the keep-live finalize. `live_window_prefix`
stays only in the offline `replay.rs`, private.
- `DRAFT_KV_STEP` and ring regrowth, `DFlash2Attention.sliding_window`
(the mask is per block now), `trace::JUNCTION_MIN_GAP`.

## Tests
- No model loads. Each test was run once with its mutation on (red) and
once off (green), on one test binary (`MUTATIONS.md`). 44 mutations:
- plan and store: `planned_checkpoints_match_splash` (CK1),
`plan_merges_points_like_configure_draft_state_plan` (JG1, PS1),
`draft_spans_match_plan_draft_context` (DS1),
`ordinary_publication_upgrades_a_checkpoint` (UP1),
`state_bytes_count_the_lineage` (TB1),
`state_below_sees_strict_ancestors_only` (SB1).
- 4-bit window: `context_window_quantizer_matches_the_kernel` (Q15),
`state_bytes_27b_geometry` (WB1),
`restore_rebuilds_the_draft_or_starts_empty` (RD1),
`rows_of_a_non_bf16_draft_store_as_bf16` (CB1).
- publish: `rolling_checkpoint_keeps_one_and_the_one_below_r` (RC1,
RP1), `cancelled_prefill_keeps_reached_states` (CN1),
`committed_blocks_register_once` (RB1).
- claims: `capture_claims_follow_state_claim` (SC1, RB2, RW1),
`refused_checkpoint_comes_from_the_lane` (FL1, FL2),
`chunk_kv_is_booked_before_its_capture` (KV1, review C1).
- resume: `junction_at_the_kv_hit` (JN1),
`dflash2_turns_resume_at_the_deepest_state` (LV1, SV1),
`a_resumed_lane_counts_no_junction` (JR1),
`a_turn_without_reuse_publishes_no_state` (RU1),
`a_paged_turn_without_a_replay_point_keeps_its_junction` (TJ1).
- units and AR: `checkpoints_go_before_ordinary_states` (CF1),
`ar_turn_restores_gdn_from_a_composite_state` (AR1).
- ring and lane: `ring_after_n_cycles_holds_the_sliding_rows` (RG1),
`ring_attention_matches_the_sliding_window` (DM1),
`lane_buffers_are_reused_between_turns` (LB1),
`length_exit_runs_no_terminal_forward` (TF1),
`idle_lane_counts_in_the_states_account` (IA1),
`aborted_turns_leave_their_lane_buffers_idle` (AB1, SD1).
- suspend: `vacate_of_a_dflash2_turn_publishes_nothing` (VC1, RK1),
`moe_suspension_replays_on_the_lane_buffers` (MVC1, MVP1).
- after the rebase:
`a_suspended_dflash2_lane_drops_its_cells_and_idles_its_ring`, dense and
MoE (R1m, RI1); `a_stop_during_the_replay_completes` (R4);
`dead_leaves_go_after_checkpoints_before_ordinary_states` (DL1, new).
- review round 2: `a_failed_window_copy_is_an_error` (EV1, EV2: a window
copy that fails on the GPU is an error, never a published state or moved
bounds), `the_idle_lane_holds_materialized_buffers` (IR1, IR2: the idle
lane keeps only materialized ring and window, so a restore credits only
real storage).
- Re-pinned: `draft_kv_ring_bytes_match_the_window_buffer_cap`,
`qwen38_27b_lane_bytes_against_splash`,
`dflash2_takes_the_one_pool_window` (numbers above).
- Gates on the squashed commit: `cargo fmt --all -- --check` and `cargo
clippy --workspace --all-targets -- -D warnings` clean. mlx-core `--lib`
(`RUST_TEST_THREADS=1`): 4,798 passed, 0 failed, 220 ignored. `cargo
test -p mlx-paged-attn --lib`: 210 passed, 8 ignored. `yarn
build:native` passed, `index.d.cts` unchanged after the copy. `yarn
typecheck` and `tsc -b --force` (23 projects) clean. `vp lint` and `vp
fmt` on `health.ts` and `health.test.ts` clean. `vp test __test__/server
packages/server packages/lm/__test__`: 1,596 passed, 7 skipped.
- Review round 2 (H1, M1): fmt and clippy clean; scoped `engine::` 587
passed, `models::qwen3_5` (dense + MoE) 594 passed, `models::qwen3::` 46
passed, 0 failed. No `#[napi]` or TS file changed.
- After the rebase onto S33 0315514: fmt and clippy clean; mlx-core
`--lib` 4,819 passed, 0 failed, 220 ignored; mlx-paged-attn 210 passed,
8 ignored; `yarn build:native` passed, `index.d.cts` unchanged; `yarn
typecheck`, `tsc -b --force` clean; `vp test` 1,596 passed, 7 skipped.
- Rebase mapping: a verify still lends its GDN cells to the target
across its claim (S11), so a suspend drops them before the wait; its
ring now goes to the idle lane instead of being dropped. The S11
dead-leaves unit now sits after the checkpoints (Splash `Phase` order),
and the stop-during-replay rule moved with the replay into
`suspended_wait`.

## Gaps
- 16-token blocks, so points round to 16 (Splash pages are 32). Ring
attention uses MLX SDPA with a per-row mask, so its summation order
differs from Splash's tiles (no bit parity).
- No shared-prefill points (Splash `addSharedPrefillBoundaries`); one
turn plan per model. The idle lane is never taken by a claim, and it is
counted in the states account but is not a ledger unit.
- No restore lease: `checkpoint_pinned` is always false. No capture is
ever Pending (no SSD state tier).
- `unprovenState` and `lostStateMisses` are not ported.
- Decode registers its blocks only at finalize, so a cancel during
decode loses the decode KV.
- A passed checkpoint is never captured as a fallback when a chunk's KV
claim is refused, and `stateCaptures` is not counted (mlx-node chunks
end at every captured point).
- A block reserve still evicts dead leaves before any checkpoint (the
allocator does it inside `reserve`); only the ledger's dead-leaves unit
follows the checkpoints.
- DFlash2 turns still publish GDN ladder rungs when a cold GDN sidecar
policy is on. AR turns keep the ladder, the history entry and the live
lane.
- After a restore claim fails, the cold turn still plans its junction.
In Splash the request is `skipCache` and plans no junction. Outputs stay
correct.
- The serial decode suspend stays in place (S11's `suspend_in_place`);
only the prefill unwinds through `DFLASH2_SUSPENDED`. The tests force
the yield with a test hook, not with host pressure, because a real
HostPressure denial first takes the checkpoints.
- The MoE prefill has no cancel hook, so there is no MoE
cancelled-prefill test.
- The target side of a paged prefill chunk still evaluates with the
error-swallowing `MxArray::eval` (`hidden_states.eval()` in
paged_forward.rs, older than this PR), so a GPU failure there is only
logged; the draft window's own copies now fail the turn (Splash
`NativeRuntime::executionFailed`).

## Not in this PR (live, not run)
- L0 sanity on the full release build; L1 teacher-forced acceptance,
fresh vs restored turn (4-bit window), S vs base; L2 turn-2 TTFT without
the live lane; L3 states after one 64K prompt (rolling checkpoints, no
budget); L4 DFlash2 decode at 8K and 64K, S vs base. Commands:
`LIVE.md`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
…inistic draft parity) (#348)

## Summary

Three precision fixes for tests that fail or flake on Apple Silicon.

| Commit | Cause | Fix |
|---|---|---|
| `fix(rerank)` 3dd3bf9 | NAX GPUs run f32 GEMMs in TF32, so batched
and single XLM-R reranker scores differ. | The reranker model thread
runs in true f32 (per-thread TF32 off, as DeepSeek V4.1 does). |
| `fix(training)` 8772608 | `sparse_moe_functional` gathered router
scores with `take_along_axis` before `stop_gradient` on the top-k
indices. Every Qwen3.5 MoE `value_and_grad` (GRPO and SFT) failed with
`[gather_axis] Cannot calculate VJP with respect to indices`. | Stop the
gradient right after the top-k slice, as `mlx-lm` `qwen3_moe.py` does. |
| `test(qwen3_5)` ccbb0e6 |
`merged_draft_projections_match_separate_bits` drew new random weights
each run (no seed). At T=8 the merged `gate\|up` matmul flips last bits;
`down_proj` spreads them over 5120 outputs, and the 5% limit sat inside
that spread. | Seed the RNG. Compare the merged `gate\|up` swiglu output
(`gated()`) with the separate path. The full output must equal
`down_proj(gated)`. |

## Evidence

- MoE autograd: 2 new tests
(`sparse_moe_value_and_grad_unsorted_branch`, `..._sorted_branch`). Red
on the old code with the VJP error, green after the fix.
- Draft parity, 1000 seeds on M5 Max: old body failed 18/1000; new body
failed 0/1000. `gated` max difference 0.10% (limit 5%).
- `cargo fmt --check`, `cargo clippy --all-targets -D warnings`, and
`cargo test -p mlx-core --lib` for the touched modules (599 passed) are
green.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
…out MPP prefills through a portable path (#377)

## Why

main CI run 43254067201 (61e72da, after #344 and #348) failed three
jobs.

| Job | Cause | CI error |
|---|---|---|
| Clippy, cargo test (mlx-core lib) | #348's `tiny_moe_config` in
`utils/functional.rs` builds `Qwen3_5MoeConfig` with two fields #344
removed and misses `rope_scaling` | `error[E0560]: struct
Qwen3_5MoeConfig has no field named paged_cache_initial_memory_mb`
(functional.rs:2032), same for `use_block_paged_cache` (2034) |
| e2e qwen3_5-dense | Since #344 the memory plan refuses an explicit
pool above its own. The test pins 512 MiB; on the macos-26 runner the
plan allows 181 MiB | `Qwen3.5: paged_cache_memory_mb 512 exceeds the
181 MiB of KV pool the model and this Mac's memory allow; omit it or set
at most 181` (p2_paged_thinking_honors_enable) |

Cargo stops at the first failing test binary, so the rest of the leg
never ran. Two more tests in it had the same problem:

| Test | Explicit pool | Result on the runner |
|---|---|---|
| `p2_paged_thinking_honors_enable` | 512 MiB | failed in CI |
| `qwen3_5_session` | 512 MiB | would fail (never ran) |
| `qwen3_5_cold_tier_parity` (harness) | 1024 MiB | would fail (never
ran) |
| `qwen3_5_delta_chat`, `qwen3_5_concurrent_batched_parity` | none |
pass |
| lib_tests (2 tiny synthetic models, 256 MiB) | inside the plan | pass
|

## Fix

- `functional.rs`: drop `paged_cache_initial_memory_mb` and
`use_block_paged_cache`, add `rope_scaling: None`. `persist_paged_cache`
still exists on main and stays. The struct now matches
`Qwen3_5MoeConfig` and `tests/common/mod.rs`.
- `p2_paged_thinking_honors_enable`, `qwen3_5_session`: stop writing
`paged_cache_memory_mb`, so the plan sizes the pool. The 512 was only
there to keep the pool small, and the pool now grows by extents.
`paged_block_size = 16` stays because the session test's prefix
assertion depends on it.
- Cold-tier harness: `pool_memory_mb` becomes `Option<u32>`. The default
stays `Some(256)`, and the new `with_planned_pool()` leaves the key out.
The qwen3_5 gate uses it: the 181 MiB planned pool holds about 15k BF16
tokens, and the gate needs two prompts of about 1,260 tokens each.
Measured: `evictions=0`.

Other legs, checked:

| Leg / test | Explicit pool | Decision |
|---|---|---|
| qwen3: `qwen3_paged_vs_flat_parity`, `qwen3_cold_tier_parity`,
`qwen3-paged-*.test.ts` | 256 | Unchanged. The leg passed on the same
runner |
| lfm2: `lfm2_paged_vs_flat_parity`, `lfm2_cold_tier_parity` | 256 |
Unchanged. The leg passed on the same runner |
| gemma4 (PR opt-in): `gemma4_grouped_cold_tier_parity` | 1024 |
Unchanged. It needs a full-context lane, and it passes under the runner
simulation below |
| nemotron_h: `*_paged_vs_flat_parity`, `*_mtp_midcycle_state` | 512 |
Unchanged. The leg is skipped on every event (needs a self-hosted
runner) |

## Local repro

Model: `yarn mlx download model -m Qwen/Qwen3.5-0.8B` + `yarn mlx
convert -d bf16 -m qwen3_5`, as in ci.yml. The runner's working set is
simulated with an uncommitted, env-switched override of
`mlx_max_recommended_working_set_size` and the
`recommendedMaxWorkingSetSize` read in `mlx_paged_dispatch.cpp`. A
working set of 5,010,305,024 B reproduces the CI message exactly (`...
exceeds the 181 MiB ...`). The whole leg ran with the CI env (`CI=true`,
`MLX_METALLIB_STRICT=1`, `MLX_TEST_REQUIRE_METAL=1` for lib_tests,
`QWEN35_STAGE2_MODEL_PATH` + `MLX_SCHED_MAX_NUM_SEQS=2` for stage2,
`--test-threads=1`), with `--no-fail-fast`.

| Run | p2 | session | cold tier | delta_chat | lib_tests | stage2 |
|---|---|---|---|---|---|---|
| simulated runner, before | FAIL (512 > 181) | FAIL (512 > 181) | FAIL
(1024 > 181) | 6/6 | 2/2 | 1/1 |
| simulated runner, after | ok | ok | ok (hits=42, corruptions=0,
evictions=0) | 6/6 | 2/2 | 1/1 |
| native M5 Max, after (simulation removed) | ok | ok | ok | 6/6 | 2/2 |
1/1 |

## Gates

| Gate | Result |
|---|---|
| `cargo fmt --all -- --check` | pass |
| `cargo clippy --workspace --all-targets -- -D warnings` | pass |
| `cargo test -p mlx-core --lib` | 4823 passed, 0 failed, 221 ignored |
| `cargo test --workspace --test '*' --no-fail-fast`
(`MLX_TEST_REQUIRE_METAL=1`) | 111 binaries, 323 passed, 0 failed |

No TS changes.

## Portable prefill path for GPUs that cannot build the MPP kernel
(34d5b06)

**Problem.** Since S10 (#368) and S10f (#369), every Qwen3.5 dense / MoE
prefill chunk and every MTP / DFlash2 verify block attends only through
the MPP tensor-op kernel
`paged_prefill_attention_{bf16,q8}_split_g*_d*`. The hosted macOS VM
cannot build those pipelines, so the e2e `qwen3_5-dense` leg failed:

```
MLX eval failed in paged_prefill_layer_barrier while materializing 1 arrays: paged prefill attention kernel paged_prefill_attention_q8_split_g4_d256 has no pipeline on no known Apple GPU family
```

**Fallback.** `PagedKVCacheAdapter::paged_prefill_attention` now goes
one of two ways:

```
device_prefill_mpp_builds()?  (asked once per process, OnceLock)
   yes -> MPP split + reduce   (unchanged)
   no  -> gather_kv_for_prefill_chunk_varlen  (vLLM varlen kernel, plain Metal, already in the tree)
```

- **How it is chosen:** the new `mlx_paged_prefill_mpp_builds()` tries
to build all 24 MPP pipelines. If any build throws, the answer is false.
Linux returns false. The answer is never taken from catching an error on
a single call.
- **Same input as MPP:** the fallback reads the same stored rows,
including int8 values times their scale.
- **One warning:** the first time the device answers no, it logs
`paged_prefill_portable`.
- **Departs from Splash on purpose:** Splash has no such fallback. The
code comment names its kernel (`kernels/prefill/paged_attention.metal`,
`paged_attention_tile.h`).
- **About 40 lines of production code.** It adds no new kernel and
restores none of the deleted route.

**Tests**

| Test | Checks |
|---|---|
| `portable_prefill_matches_the_tile_kernel` | Fallback and MPP against
an f64 reference, within Splash's `checkOutput` bound. Pools: int8 and
bf16. Geometry: g4/D128, g8/D256, g16/D256. Cases (committed, rows): (0,
40), (40, 24), (600, 9) (past the 512-token switch), and a 5-row verify.
Largest difference between fallback and MPP: 0.25 (values carry ×60
outliers). On the VM it runs the fallback half only. |
| `prefill_routes_once_and_to_mpp_where_it_builds` | MPP is launched
once per chunk wherever it builds, and the device is asked exactly once
per process. |
| `portable_prefill_turn_matches_the_tile_turn` | Tiny seeded model,
70-token prompt, 16 greedy steps, bf16 pool (D128) and int8 pool (D256).
Logits stay within 0.02 (measured 0.0098 / 0.0078). With a tie screen,
16 of 16 tokens are equal. |
| `paged_attention_reads_its_own_rows_back` | Refactored onto the shared
reference helper; unchanged. |

**Mutations** (one build, runtime switches, removed before the commit)

| Id | Mutation | Red test | Failure |
|---|---|---|---|
| PF1 | Always take the fallback | routes test | `one tile launch per
chunk`, left 0, right 2 |
| PF2 | Fallback at `committed - 1` | parity test | Int8 8/2 D128 P 40 T
24: worst error 121 × bound |
| PF3 | Probe skips the OnceLock | routes test | asked 3 times, expected
1 |

All three passed with the switch off.

**VM simulation** (uncommitted; removed). It forces the working set to
5,010,305,024 B, makes every MPP pipeline throw the CI error text, and
makes `mlx_test_gpu_lacks_apple_family` return true. Each run is the
full `qwen3_5-dense` leg as `ci.yml` runs it.

| Run | Integration (4 binaries) | lib_tests | stage2 | "has no
pipeline" lines |
|---|---|---|---|---|
| sim, before (bf19716) | 0/1, 0/1, 1/6, 0/1 FAILED | 0/2 FAILED | 0/1
FAILED | 11 (the CI error, reproduced) |
| sim, with fallback | 1/1, 1/1, 6/6, 1/1 | 2/2, no `skipping` | 1/1 | 0
|
| native M5, sim removed | 1/1, 1/1, 6/6, 1/1 | 2/2, no `skipping` | 1/1
| 0 |

**Gates** (logs in
`/Volumes/PM9A1/claude-scratchpad/7e002cb3-kv-int8/fallback/`)

| Gate | Result |
|---|---|
| `cargo fmt --all -- --check` | ok (`gate-fmt.log`) |
| `cargo clippy --workspace --all-targets -D warnings` | ok
(`gate-clippy2.log`) |
| `cargo test -p mlx-core --lib` | 4826 passed, 0 failed
(`gate-lib.log`) |
| `cargo test -p mlx-paged-attn` | 334 passed (`gate-paged-attn.log`) |
| `cargo test --workspace --test '*' --no-fail-fast` | 323 passed, 0
failed (`gate-int.log`) |
| Live T=0 smoke, qwen3.5-0.8b (MPP), serial + scheduler, chunk 64 |
byte-equal to before (`smoke-{before,after}-*.json`) |

No `#[napi]` change, so no `index.d.cts` update.

**Known gaps**
- **bf16 scratch is not charged.** On a fallback device with a bf16
pool, the varlen partials are not charged by the memory plan: about
`rows × Hq × ceil(ctx/512) × (D+2) × 4 B`. int8 is bounded by the
kernel's 2,048 row-partition tiling.
- **Not bit-equal to MPP.** Tokens can differ at bf16 ties between a
device that builds MPP and one that does not. On one device the route
never changes.
- **Not yet run on the real VM.** The int8 varlen pipelines have not run
on the hosted VM; only CI can confirm it accepts them.
- **M1 / M2 still untested.** They take MPP if all 24 pipelines build,
otherwise the fallback.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
…ssified (#379)

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](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
> [!NOTE]
> This PR body was truncated due to platform limits.

This PR contains the following updates:

| Package | Change |
[Age](https://docs.renovatebot.com/merge-confidence/) |
[Confidence](https://docs.renovatebot.com/merge-confidence/) |
|---|---|---|---|
| [got](https://redirect.github.com/sindresorhus/got) | [`^11.8.6` →
`^16.0.0`](https://renovatebot.com/diffs/npm/got/11.8.6/16.2.0) |
![age](https://developer.mend.io/api/mc/badges/age/npm/got/16.2.0?slim=true)
|
![confidence](https://developer.mend.io/api/mc/badges/confidence/npm/got/11.8.6/16.2.0?slim=true)
|

---

### Release Notes

<details>
<summary>sindresorhus/got (got)</summary>

###
[`v16.2.0`](https://redirect.github.com/sindresorhus/got/releases/tag/v16.2.0)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v16.1.0...v16.2.0)

- Add Standard Schema support to `.json()`
([#&#8203;2477](https://redirect.github.com/sindresorhus/got/issues/2477))
[`d6fb3bd`](https://redirect.github.com/sindresorhus/got/commit/d6fb3bda)

***

###
[`v16.1.0`](https://redirect.github.com/sindresorhus/got/releases/tag/v16.1.0)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v16.0.0...v16.1.0)

This release is the result of a large bug hunt. Many of the fixes make
Got match its documented behavior, so you may notice some of them:

- Invalid options now throw: an empty `method`, a negative or fractional
`maxRedirects` or `retry.limit`, a `prefixUrl` with a query string or
fragment, and a `handlers` entry that is not a function.
- A stream with a `body`, `json`, or `form` option now rejects writes,
as documented.
- The promise `response` event now only fires for the final response,
not for every retry attempt.
- `got.extend({body})` (and `json`, `form`) no longer sends the payload
with every request of the instance. Payloads are never merged with
defaults.
- `instance.extend()` now inherits the parent's `mutableDefaults`, like
`got.extend(instance)`.
- A `HEAD` request is no longer changed to `GET` on a `301`, `302`, or
`303` redirect.
- `response.body` no longer keeps a leading UTF-8 byte order mark, and
JSON with a byte order mark now parses.

#### Improvements

- Accept number values in `headers`
[`6fffc9e`](https://redirect.github.com/sindresorhus/got/commit/6fffc9e)
- Export the `Timings`, `DnsCacheLookup`, and `DnsCacheOptions` types
[`d012d1d`](https://redirect.github.com/sindresorhus/got/commit/d012d1d)
[`eccaaca`](https://redirect.github.com/sindresorhus/got/commit/eccaaca)
- Retry `FormData` bodies by re-serializing them instead of failing
[`90c6ec1`](https://redirect.github.com/sindresorhus/got/commit/90c6ec1)
- Support the `x-gzip` content coding and stacked content codings
[`5550a79`](https://redirect.github.com/sindresorhus/got/commit/5550a79)

#### Fixes

- Fix many HTTP/2 edge cases, including requests that could hang forever
when the response or request was destroyed
[`d3c549c`](https://redirect.github.com/sindresorhus/got/commit/d3c549c)
[`78bf394`](https://redirect.github.com/sindresorhus/got/commit/78bf394)
[`6bbc7f4`](https://redirect.github.com/sindresorhus/got/commit/6bbc7f4)
[`602b179`](https://redirect.github.com/sindresorhus/got/commit/602b179)
[`687b5c8`](https://redirect.github.com/sindresorhus/got/commit/687b5c8)
[`4ea02b8`](https://redirect.github.com/sindresorhus/got/commit/4ea02b8)
[`b6522f3`](https://redirect.github.com/sindresorhus/got/commit/b6522f3)
[`9348ad6`](https://redirect.github.com/sindresorhus/got/commit/9348ad6)
[`c686386`](https://redirect.github.com/sindresorhus/got/commit/c686386)
[`3bbc37b`](https://redirect.github.com/sindresorhus/got/commit/3bbc37b)
[`91dc486`](https://redirect.github.com/sindresorhus/got/commit/91dc486)
[`11621cd`](https://redirect.github.com/sindresorhus/got/commit/11621cd)
- Fix `timeout.request` restarting on each redirect, and several timeout
phase edge cases
[`9cd2ee6`](https://redirect.github.com/sindresorhus/got/commit/9cd2ee6)
[`df33cdb`](https://redirect.github.com/sindresorhus/got/commit/df33cdb)
[`4e4c583`](https://redirect.github.com/sindresorhus/got/commit/4e4c583)
[`795234f`](https://redirect.github.com/sindresorhus/got/commit/795234f)
[`0f1263d`](https://redirect.github.com/sindresorhus/got/commit/0f1263d)
- Fix redirects: keep the URL fragment, evaluate `followRedirect` once
per response, and keep `Content-Length` correct when a hook replaces the
body
[`1febf3c`](https://redirect.github.com/sindresorhus/got/commit/1febf3c)
[`a2b3d90`](https://redirect.github.com/sindresorhus/got/commit/a2b3d90)
[`1d64f7c`](https://redirect.github.com/sindresorhus/got/commit/1d64f7c)
[`60b48af`](https://redirect.github.com/sindresorhus/got/commit/60b48af)
- Fix `Infinity` timeouts firing at once or throwing
[`724ebc2`](https://redirect.github.com/sindresorhus/got/commit/724ebc2)
- Fix retry delay edge cases, including invalid `Retry-After` values and
`calculateDelay` for `afterResponse` retries
[`fe58b8c`](https://redirect.github.com/sindresorhus/got/commit/fe58b8c)
[`0193605`](https://redirect.github.com/sindresorhus/got/commit/0193605)
- Fix retries with replaced or non-replayable bodies
[`ae5521f`](https://redirect.github.com/sindresorhus/got/commit/ae5521f)
[`7c1cda3`](https://redirect.github.com/sindresorhus/got/commit/7c1cda3)
[`8bbc79f`](https://redirect.github.com/sindresorhus/got/commit/8bbc79f)
[`1a56d36`](https://redirect.github.com/sindresorhus/got/commit/1a56d36)
[`d012d1d`](https://redirect.github.com/sindresorhus/got/commit/d012d1d)
- Fix the default `paginate` on real-world `Link` headers, and several
pagination option and limit edge cases
[`bd2dee0`](https://redirect.github.com/sindresorhus/got/commit/bd2dee0)
[`1e61807`](https://redirect.github.com/sindresorhus/got/commit/1e61807)
[`602b179`](https://redirect.github.com/sindresorhus/got/commit/602b179)
[`f98d0e1`](https://redirect.github.com/sindresorhus/got/commit/f98d0e1)
[`c8419e4`](https://redirect.github.com/sindresorhus/got/commit/c8419e4)
[`526a988`](https://redirect.github.com/sindresorhus/got/commit/526a988)
[`557e61f`](https://redirect.github.com/sindresorhus/got/commit/557e61f)
[`4712e5b`](https://redirect.github.com/sindresorhus/got/commit/4712e5b)
[`a4a50ad`](https://redirect.github.com/sindresorhus/got/commit/a4a50ad)
[`b65e533`](https://redirect.github.com/sindresorhus/got/commit/b65e533)
- Fix `afterResponse`, `beforeRequest`, and `beforeCache` hook edge
cases
[`45c201c`](https://redirect.github.com/sindresorhus/got/commit/45c201c)
[`c1cf0f8`](https://redirect.github.com/sindresorhus/got/commit/c1cf0f8)
[`850e49b`](https://redirect.github.com/sindresorhus/got/commit/850e49b)
[`a4a50ad`](https://redirect.github.com/sindresorhus/got/commit/a4a50ad)
[`863cf30`](https://redirect.github.com/sindresorhus/got/commit/863cf30)
[`494279b`](https://redirect.github.com/sindresorhus/got/commit/494279b)
- Fix response body decoding and parsing edge cases
[`c36ad51`](https://redirect.github.com/sindresorhus/got/commit/c36ad51)
[`c409a84`](https://redirect.github.com/sindresorhus/got/commit/c409a84)
[`3c6eaf1`](https://redirect.github.com/sindresorhus/got/commit/3c6eaf1)
[`f658d3e`](https://redirect.github.com/sindresorhus/got/commit/f658d3e)
[`dbd83df`](https://redirect.github.com/sindresorhus/got/commit/dbd83df)
- Fix stream edge cases: respect backpressure, stop forwarding after
unpipe, and do not copy hop-by-hop headers to a piped `ServerResponse`
[`348e114`](https://redirect.github.com/sindresorhus/got/commit/348e114)
[`dc929bd`](https://redirect.github.com/sindresorhus/got/commit/dc929bd)
[`dc56e4b`](https://redirect.github.com/sindresorhus/got/commit/dc56e4b)
[`c930cd9`](https://redirect.github.com/sindresorhus/got/commit/c930cd9)
[`a9a754f`](https://redirect.github.com/sindresorhus/got/commit/a9a754f)
- Fix uploads: `DataView` byte ranges, upload error classification,
progress `total` for `Content-Length: 0`, and cancelling Web
`ReadableStream` bodies
[`2a66686`](https://redirect.github.com/sindresorhus/got/commit/2a66686)
[`d1cb051`](https://redirect.github.com/sindresorhus/got/commit/d1cb051)
[`0238069`](https://redirect.github.com/sindresorhus/got/commit/0238069)
[`b57120c`](https://redirect.github.com/sindresorhus/got/commit/b57120c)
[`200bc85`](https://redirect.github.com/sindresorhus/got/commit/200bc85)
- Fix option normalization, cloning, and immutable defaults
[`8f44d81`](https://redirect.github.com/sindresorhus/got/commit/8f44d81)
[`687eb7d`](https://redirect.github.com/sindresorhus/got/commit/687eb7d)
[`30023f7`](https://redirect.github.com/sindresorhus/got/commit/30023f7)
[`5548b00`](https://redirect.github.com/sindresorhus/got/commit/5548b00)
[`bec5da6`](https://redirect.github.com/sindresorhus/got/commit/bec5da6)
[`bcc0b01`](https://redirect.github.com/sindresorhus/got/commit/bcc0b01)
[`9348ad6`](https://redirect.github.com/sindresorhus/got/commit/9348ad6)
[`a9a754f`](https://redirect.github.com/sindresorhus/got/commit/a9a754f)
[`7b13369`](https://redirect.github.com/sindresorhus/got/commit/7b13369)
[`3bd0486`](https://redirect.github.com/sindresorhus/got/commit/3bd0486)
[`d272656`](https://redirect.github.com/sindresorhus/got/commit/d272656)
[`0e537c7`](https://redirect.github.com/sindresorhus/got/commit/0e537c7)
[`60b62a0`](https://redirect.github.com/sindresorhus/got/commit/60b62a0)
[`129d88d`](https://redirect.github.com/sindresorhus/got/commit/129d88d)
- Fix error stacks reporting `RequestError` instead of the real error
class, and other error cause edge cases
[`c8419e4`](https://redirect.github.com/sindresorhus/got/commit/c8419e4)
[`9d61a37`](https://redirect.github.com/sindresorhus/got/commit/9d61a37)
[`5ccac58`](https://redirect.github.com/sindresorhus/got/commit/5ccac58)
[`71f4e0e`](https://redirect.github.com/sindresorhus/got/commit/71f4e0e)
- Fix custom DNS cache lookups and DNS records without a valid TTL
[`b3dc5c6`](https://redirect.github.com/sindresorhus/got/commit/b3dc5c6)
[`4ea02b8`](https://redirect.github.com/sindresorhus/got/commit/4ea02b8)
[`d012d1d`](https://redirect.github.com/sindresorhus/got/commit/d012d1d)
- Fix cookie edge cases with retries, redirects, and async cookie jars
[`784bbd2`](https://redirect.github.com/sindresorhus/got/commit/784bbd2)
[`d5cd5e4`](https://redirect.github.com/sindresorhus/got/commit/d5cd5e4)
- Fix diagnostics channel coverage across retries and terminal errors
[`cfce7b6`](https://redirect.github.com/sindresorhus/got/commit/cfce7b6)
- Fix TypeScript types to match the runtime values
[`7c833b8`](https://redirect.github.com/sindresorhus/got/commit/7c833b8)
[`c59692b`](https://redirect.github.com/sindresorhus/got/commit/c59692b)
[`88eeb13`](https://redirect.github.com/sindresorhus/got/commit/88eeb13)
[`0c17a8b`](https://redirect.github.com/sindresorhus/got/commit/0c17a8b)
[`c788ac9`](https://redirect.github.com/sindresorhus/got/commit/c788ac9)
[`a4176b6`](https://redirect.github.com/sindresorhus/got/commit/a4176b6)

***

###
[`v16.0.0`](https://redirect.github.com/sindresorhus/got/releases/tag/v16.0.0)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v15.1.0...v16.0.0)

#### Breaking changes

- Rewrite HTTP/2 support and drop the `http2-wrapper` dependency
([#&#8203;2464](https://redirect.github.com/sindresorhus/got/issues/2464))
[`1e157c4`](https://redirect.github.com/sindresorhus/got/commit/1e157c4)
- Got now has a built-in HTTP/2 client: ALPN negotiation, a pooled
session cache with multiplexing, `GOAWAY` retirement, request and
response trailers, informational (1xx) responses, abort signals,
response caching, IPv6 authorities, and `h2c` through `h2session`.
- `agent.http2` is no longer an agent slot. It is only an opt-out flag
now: pass `false` to skip session pooling. Passing an agent instance
throws.
- Response headers no longer contain HTTP/2 pseudo-headers. Use
`response.statusCode` instead of `response.headers[':status']`.
- A custom `agent.https` combined with `http2: true` makes Got use the
native HTTP/1.1 path, because the built-in session pool does not support
custom HTTPS agents.
- HTTP/2 proxy support is gone. It came from `http2-wrapper`. It was
very buggy anyway.
- If `options.request` returns a request or response, it controls the
transport and the HTTP/2 client is bypassed. Return `undefined` to fall
back to Got's own transport.
- Rewrite DNS cache and drop the `cacheable-lookup` dependency
([#&#8203;2463](https://redirect.github.com/sindresorhus/got/issues/2463))
[`bfc400b`](https://redirect.github.com/sindresorhus/got/commit/bfc400b)
- `dnsCache: true` now uses Got's own cache. The option accepts any
object with a `lookup` function and an optional `clear(hostname?)`
function, so an existing `CacheableLookup` instance still works if you
keep the dependency yourself.
- The built-in cache resolves A and AAAA records separately, so it
cannot preserve OS-specific `verbatim` address ordering from
`dns.lookup()`.
- A `beforeRequest` hook, an `afterResponse` retry, or a pagination step
that moves the request to a different origin now strips credentials and
drops the body
([#&#8203;2465](https://redirect.github.com/sindresorhus/got/issues/2465))
[`dd3b295`](https://redirect.github.com/sindresorhus/got/commit/dd3b295)
- `authorization`, `cookie`, `cookie2`, `host`, and
`proxy-authorization` are removed, URL credentials are dropped, and an
unchanged body is cleared. Set the headers or body explicitly inside the
hook if you want them to cross the origin boundary.
- This applies whether the origin changes through `url` or through
`prefixUrl`.
- `copyPipedHeaders` no longer copies credentials
[`1d233ba`](https://redirect.github.com/sindresorhus/got/commit/1d233ba)
- `authorization`, `cookie`, `cookie2`, `set-cookie`, and `set-cookie2`
are now omitted along with `host`, the hop-by-hop headers, and anything
nominated by `Connection` / `Proxy-Connection`. Pass credentials
explicitly in `headers` when the upstream is trusted.
- Remove the deprecated `searchParameters`, `followRedirects`, and
`auth` option stubs
[`1d233ba`](https://redirect.github.com/sindresorhus/got/commit/1d233ba)
- They only existed to throw a guidance message. Passing them now throws
`Unexpected option: …`.
- Remove the `OptionsOfUnknownResponseBody` type
[`1d233ba`](https://redirect.github.com/sindresorhus/got/commit/1d233ba)
  - It was a pure alias for `StrictOptions`.

#### Improvements

- Add support for the
[`QUERY`](https://www.rfc-editor.org/rfc/rfc10008.html) HTTP method
([#&#8203;2466](https://redirect.github.com/sindresorhus/got/issues/2466))
[`e3924aa`](https://redirect.github.com/sindresorhus/got/commit/e3924aa)
- Adds `got.query()` and `got.stream.query()`. `QUERY` is safe and
idempotent, so it is retried by default and keeps a replayable body
across `301` and `302` redirects as well as `307` and `308`. It is not
stored by the built-in cache, because correct `QUERY` caching needs
cache keys that include the request content.
- `allowGetBody` now also works over HTTP/2
[`1e157c4`](https://redirect.github.com/sindresorhus/got/commit/1e157c4)
- `timeout.socket` now applies during HTTP/2 TLS negotiation and session
setup
[`c6bbb8a`](https://redirect.github.com/sindresorhus/got/commit/c6bbb8a)
- It was previously folded into the connection setup timeout and
reported as a `request` timeout. It now produces a real `socket` timeout
and no longer counts DNS lookup time.
- Two fewer dependencies: `cacheable-lookup` and `http2-wrapper`
[`bfc400b`](https://redirect.github.com/sindresorhus/got/commit/bfc400b)
[`1e157c4`](https://redirect.github.com/sindresorhus/got/commit/1e157c4)

#### Fixes

- Retry on connection errors reported by `request.end()` instead of
failing the request
([#&#8203;2470](https://redirect.github.com/sindresorhus/got/issues/2470))
[`67919b2`](https://redirect.github.com/sindresorhus/got/commit/67919b2)
- Retry immediately when the server answers with `Retry-After: 0`
instead of falling back to the backoff delay
([#&#8203;2471](https://redirect.github.com/sindresorhus/got/issues/2471))
[`d35ce87`](https://redirect.github.com/sindresorhus/got/commit/d35ce87)
- Preserve the response body when a cookie jar write throws
[`c6bbb8a`](https://redirect.github.com/sindresorhus/got/commit/c6bbb8a)
- `error.response.body` is now complete, decompressed, and decoded with
the configured `encoding`, and a decoding failure no longer masks the
original error.
- Wait for async cookie jar writes on terminal redirect responses, for
example with `followRedirect: false`
[`c6bbb8a`](https://redirect.github.com/sindresorhus/got/commit/c6bbb8a)
- Only buffer the response body for cookie handling when the response
actually sends `set-cookie`
[`c6bbb8a`](https://redirect.github.com/sindresorhus/got/commit/c6bbb8a)
- Fix `got.stream` finalizing the response before the `response` event
and before piped server response headers are set
[`c6bbb8a`](https://redirect.github.com/sindresorhus/got/commit/c6bbb8a)
- Fix `strictContentLength` counting bytes from responses that were not
actually decompressed
[`c6bbb8a`](https://redirect.github.com/sindresorhus/got/commit/c6bbb8a)
- Freeze `hooks.beforeCache` along with the other hook arrays on
non-mutable defaults
[`1d233ba`](https://redirect.github.com/sindresorhus/got/commit/1d233ba)
- Keep URL credentials when `prefixUrl` is changed to a same-origin
value, and treat credentials in `prefixUrl` as explicit
[`dd3b295`](https://redirect.github.com/sindresorhus/got/commit/dd3b295)

#### Migration guide

##### HTTP/2

Remove `http2-wrapper` from your code. Got's HTTP/2 client is built in.

**Before:**

```js
import http2wrapper from 'http2-wrapper';

const {headers} = await got(url, {
	http2: true,
	request: http2wrapper.auto,
	agent: {
		http2: new http2wrapper.Agent()
	}
});

console.log(headers[':status']);
```

**After:**

```js
const {statusCode} = await got(url, {http2: true});

console.log(statusCode);
```

To opt out of HTTP/2 session pooling for a request, set `agent.http2` to
`false`.

If you need an HTTP/2 proxy, keep using `http2-wrapper` through the
`request` option. Returning a request from `request` bypasses Got's
HTTP/2 client.

##### `h2c`

The `h2session` hook example no longer needs `request` or `http2`.

**Before:**

```js
import http2 from 'http2-wrapper';

got.extend({
	hooks: {
		beforeRequest: [
			options => {
				options.h2session = getSession(options.url);
				options.http2 = true;
				options.request = http2.request;
			}
		]
	}
});
```

**After:**

```js
got.extend({
	hooks: {
		beforeRequest: [
			options => {
				options.h2session = getSession(options.url);
			}
		]
	}
});
```

##### `dnsCache`

`dnsCache: true` keeps working and now uses Got's built-in cache. If you
depend on `cacheable-lookup` specific options, install it yourself and
pass the instance:

```js
import CacheableLookup from 'cacheable-lookup';

const dnsCache = new CacheableLookup({maxTtl: 60});

await got(url, {dnsCache});
```

##### Cross-origin hooks

If a `beforeRequest` hook, an `afterResponse` retry, or a pagination
step sends the request to a different origin, set the headers and body
you want to keep explicitly:

```js
got.extend({
	hooks: {
		beforeRequest: [
			options => {
				options.url = new URL('https://other.example.com/path');
				options.headers.authorization = 'Bearer …';
			}
		]
	}
});
```

##### `copyPipedHeaders`

Credentials are no longer forwarded from a piped request. Pass them
explicitly when the upstream is trusted:

```js
got.stream(url, {
	copyPipedHeaders: true,
	headers: {
		authorization: request.headers.authorization
	}
});
```

***

###
[`v15.1.0`](https://redirect.github.com/sindresorhus/got/releases/tag/v15.1.0)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v15.0.7...v15.1.0)

- Add
[`allowAbsoluteUrls`](https://redirect.github.com/sindresorhus/got/blob/main/documentation/2-options.md#allowabsoluteurls)
option
([#&#8203;2462](https://redirect.github.com/sindresorhus/got/issues/2462))
[`1c88e88`](https://redirect.github.com/sindresorhus/got/commit/1c88e88)

***

###
[`v15.0.7`](https://redirect.github.com/sindresorhus/got/releases/tag/v15.0.7)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v15.0.6...v15.0.7)

- Fix: Preserve request body on cross-origin 307 and 308 redirects
([#&#8203;2460](https://redirect.github.com/sindresorhus/got/issues/2460))
[`aee9249`](https://redirect.github.com/sindresorhus/got/commit/aee9249)

***

###
[`v15.0.6`](https://redirect.github.com/sindresorhus/got/releases/tag/v15.0.6)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v15.0.5...v15.0.6)

- Fix `searchParams` setter dropping the value when a URL is set
([#&#8203;2454](https://redirect.github.com/sindresorhus/got/issues/2454))
[`5772bf2`](https://redirect.github.com/sindresorhus/got/commit/5772bf2)

***

###
[`v15.0.5`](https://redirect.github.com/sindresorhus/got/releases/tag/v15.0.5)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v15.0.4...v15.0.5)

- Fix: Handle abort signals added by handlers
[`74e3167`](https://redirect.github.com/sindresorhus/got/commit/74e3167)

***

###
[`v15.0.4`](https://redirect.github.com/sindresorhus/got/releases/tag/v15.0.4)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v15.0.3...v15.0.4)

- Fix aborting during download progress
[`11a2202`](https://redirect.github.com/sindresorhus/got/commit/11a2202)

***

###
[`v15.0.3`](https://redirect.github.com/sindresorhus/got/releases/tag/v15.0.3)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v15.0.2...v15.0.3)

- Fix false `ReadError` on responses without `Content-Length`
[`071ea07`](https://redirect.github.com/sindresorhus/got/commit/071ea07)

***

###
[`v15.0.2`](https://redirect.github.com/sindresorhus/got/releases/tag/v15.0.2)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v15.0.1...v15.0.2)

- Fix stream cookie jar completion race
[`b170125`](https://redirect.github.com/sindresorhus/got/commit/b170125)

***

###
[`v15.0.1`](https://redirect.github.com/sindresorhus/got/releases/tag/v15.0.1)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v15.0.0...v15.0.1)

- Fix init types
[`20633bc`](https://redirect.github.com/sindresorhus/got/commit/20633bc)

***

###
[`v15.0.0`](https://redirect.github.com/sindresorhus/got/releases/tag/v15.0.0)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v14.6.6...v15.0.0)

#### Breaking changes

- Require Node.js 22
[`b933476`](https://redirect.github.com/sindresorhus/got/commit/b933476)
- Remove promise cancel API
[`a06ac6c`](https://redirect.github.com/sindresorhus/got/commit/a06ac6c)
- `promise.cancel()` is gone. Use the [`signal`
option](https://redirect.github.com/sindresorhus/got/blob/main/documentation/2-options.md#signal)
with
[`AbortController`](https://developer.mozilla.org/docs/Web/API/AbortController)
instead.
- Remove `isStream` option
[`c241c6c`](https://redirect.github.com/sindresorhus/got/commit/c241c6c)
  - Use `got.stream()` directly.
- Use native `FormData` global
[`670b228`](https://redirect.github.com/sindresorhus/got/commit/670b228)
- Use the [Web API
`FormData`](https://developer.mozilla.org/docs/Web/API/FormData) global
directly (available in Node.js 18+).
- `responseType: 'buffer'` returns `Uint8Array` instead of `Buffer`
[`309e36d`](https://redirect.github.com/sindresorhus/got/commit/309e36d)
- `response.rawBody` and `promise.buffer()` now return a `Uint8Array`.
`Buffer` is a subclass of `Uint8Array`, so most code will continue to
work, but strict type checks will need updating.
- `strictContentLength` defaults to `true`
[`08e9dff`](https://redirect.github.com/sindresorhus/got/commit/08e9dff)
- Got now throws a `ContentLengthMismatchError` by default if
`Content-Length` doesn't match the actual body size. Set
`{strictContentLength: false}` to restore the old behavior.
- `retry.enforceRetryRules` defaults to `true`
[`9bc8dfb`](https://redirect.github.com/sindresorhus/got/commit/9bc8dfb)
- Custom `calculateDelay` functions are now only called when a retry is
actually allowed by `limit`, `methods`, `statusCodes`, and `errorCodes`.
If your `calculateDelay` was previously used to override retry
eligibility unconditionally, set `{retry: {enforceRetryRules: false}}`.
- Piped header copying is now opt-in
[`8e392f3`](https://redirect.github.com/sindresorhus/got/commit/8e392f3)
- Got no longer automatically copies headers from a piped stream. Set
`{copyPipedHeaders: true}` to re-enable. Hop-by-hop headers are never
copied even when enabled (RFC 9110 §7.6.1).
- `url` removed from public options objects
[`87de8d6`](https://redirect.github.com/sindresorhus/got/commit/87de8d6)
- The `url` property is no longer present on the options object passed
to hooks. Use `response.url` or `request.requestUrl` instead.
- 300 and 304 responses are no longer auto-followed
[`5fccaab`](https://redirect.github.com/sindresorhus/got/commit/5fccaab)
- Per RFC 9110, 304 is a conditional-GET hint, not a redirect, and 300
is only a SHOULD for user agents. Got now returns these responses as-is.
Handle them manually if needed.
- Removed the undocumented named export for Got.
- Got has always been a default export. The named export was there only
for buggy build tools during the ESM migration times.

#### Improvements

- Stream decode large `text`/`json` bodies incrementally for lower peak
memory usage
[`c9a95b1`](https://redirect.github.com/sindresorhus/got/commit/c9a95b1)
- `uploadProgress` now emits granular per-chunk events for `json` and
`form` request bodies
[`13c889d`](https://redirect.github.com/sindresorhus/got/commit/13c889d)

***

#### Migration guide

##### Replace `promise.cancel()` with `AbortController`

**Before:**

```js
const promise = got(url);
promise.cancel();
```

**After:**

```js
const controller = new AbortController();
const promise = got(url, {signal: controller.signal});
controller.abort();
```

##### Replace `isStream: true` with `got.stream()`

**Before:**

```js
got(url, {isStream: true});
```

**After:**

```js
got.stream(url);
```

##### Replace `form-data` / `form-data-encoder` with native `FormData`

**Before:**

```js
import {FormData} from 'formdata-node';
// or: import {FormData} from 'formdata-polyfill/esm.min.js';

const form = new FormData();
form.set('name', 'value');
await got.post(url, {body: form});
```

**After:**

```js
const form = new FormData();
form.set('name', 'value');
await got.post(url, {body: form});
```

##### Update `Buffer` usage to `Uint8Array`

`response.rawBody` and `promise.buffer()` now return `Uint8Array`
instead of `Buffer`.

**Before:**

```js
const data = await got(url).buffer();
const copy = Buffer.from(data);
```

**After:**

```js
const data = await got(url).buffer();
const copy = new Uint8Array(data);
```

If you need `Buffer`-specific APIs, wrap with `Buffer.from(data.buffer,
data.byteOffset, data.byteLength)`.

##### `strictContentLength` is now on by default

If you send requests where the `Content-Length` header might not match
the actual body size, opt out:

```js
got.extend({strictContentLength: false});
```

##### `retry.enforceRetryRules` is now on by default

If your `calculateDelay` function was overriding retry eligibility (e.g.
retrying on methods or status codes outside the defaults), opt out:

```js
got.extend({
	retry: {
		enforceRetryRules: false,
		calculateDelay: ({computedValue}) => {
			// computedValue is 0 when retry is not allowed
			if (computedValue === 0) {
				return 0;
			}

			return computedValue;
		},
	},
});
```

##### Piped header copying is now opt-in

If you pipe streams into Got and rely on automatic header forwarding
(e.g. `Content-Type`), re-enable it:

```js
got.extend({copyPipedHeaders: true});
```

##### 300 and 304 responses are no longer followed

If your code depended on Got auto-following 300 Multi-Choice or handling
304 Not Modified as a redirect, you now need to handle them yourself in
an `afterResponse` hook or check `response.statusCode` manually.

***

###
[`v14.6.6`](https://redirect.github.com/sindresorhus/got/releases/tag/v14.6.6)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v14.6.5...v14.6.6)

- Fix stream auto-end for empty PATCH/DELETE/OPTIONS
[`4d5168c`](https://redirect.github.com/sindresorhus/got/commit/4d5168c)
- The bug was introduced in
[`b65b0e1`](https://redirect.github.com/sindresorhus/got/commit/b65b0e1c300d745eb6956a4fb0bd19f3b177e144),
where it incorrectly auto-closed streams for empty PATCH/DELETE/OPTIONS
when using streams. This broke the documented use case of piping data
*to* a got stream for these methods.
  - Docs:
> `got.stream` does not auto-end for `OPTIONS`, `DELETE`, or `PATCH` so
you can pipe or write a body without getting `write after end`. Call
`stream.end()` when you are not piping a body.

***

###
[`v14.6.5`](https://redirect.github.com/sindresorhus/got/releases/tag/v14.6.5)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v14.6.4...v14.6.5)

- Fix TypeScript type inference for `got.extend()` with `responseType`
option
[`f7ab6e9`](https://redirect.github.com/sindresorhus/got/commit/f7ab6e9)

***

###
[`v14.6.4`](https://redirect.github.com/sindresorhus/got/releases/tag/v14.6.4)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v14.6.3...v14.6.4)

- Fix `dnsLookup` option type to accept Node.js `dns.lookup`
[`47c3155`](https://redirect.github.com/sindresorhus/got/commit/47c3155)

***

###
[`v14.6.3`](https://redirect.github.com/sindresorhus/got/releases/tag/v14.6.3)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v14.6.2...v14.6.3)

- Fix socket reuse timing and DNS timing
[`fb03d84`](https://redirect.github.com/sindresorhus/got/commit/fb03d84)
[`61d5e3b`](https://redirect.github.com/sindresorhus/got/commit/61d5e3b)

***

###
[`v14.6.2`](https://redirect.github.com/sindresorhus/got/releases/tag/v14.6.2)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v14.6.1...v14.6.2)

- Fix path segments containing colons being misidentified as absolute
URLs
[`0a16a9c`](https://redirect.github.com/sindresorhus/got/commit/0a16a9c)

***

###
[`v14.6.1`](https://redirect.github.com/sindresorhus/got/releases/tag/v14.6.1)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v14.6.0...v14.6.1)

- Fix the TS code not being built in 14.6.0.

***

###
[`v14.6.0`](https://redirect.github.com/sindresorhus/got/releases/tag/v14.6.0)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v14.5.0...v14.6.0)

##### Improvements

- Add
[`beforeCache`](https://redirect.github.com/sindresorhus/got/blob/599ae74e9f2a002eade81a0ec1722cf7dc28a9cd/documentation/9-hooks.md?plain=1#L237)
hook
[`1c3a041`](https://redirect.github.com/sindresorhus/got/commit/1c3a041)
- Add `retryCount` to `beforeRequest` hook context
[`91cdc48`](https://redirect.github.com/sindresorhus/got/commit/91cdc48)
- Improve `HTTPError` message to include method and URL
[`6dd7574`](https://redirect.github.com/sindresorhus/got/commit/6dd7574)
- Add support for typed arrays as request body
[`ecf5633`](https://redirect.github.com/sindresorhus/got/commit/ecf5633)
- Add Node.js [diagnostic channel
support](https://redirect.github.com/sindresorhus/got/blob/599ae74e9f2a002eade81a0ec1722cf7dc28a9cd/documentation/diagnostics-channel.md)
[`3e2a781`](https://redirect.github.com/sindresorhus/got/commit/3e2a781)
- Allow custom Error classes in `beforeError` hook
[`1c71194`](https://redirect.github.com/sindresorhus/got/commit/1c71194)
- Add zstd (Zstandard) compression support
[`449833a`](https://redirect.github.com/sindresorhus/got/commit/449833a)
- Improve validation error messages by including option names
[`f5c54a3`](https://redirect.github.com/sindresorhus/got/commit/f5c54a3)
- Add
[`strictContentLength`](https://redirect.github.com/sindresorhus/got/blob/599ae74e9f2a002eade81a0ec1722cf7dc28a9cd/documentation/2-options.md?plain=1#L854)
option
[`4206f0e`](https://redirect.github.com/sindresorhus/got/commit/4206f0e)
- Add support for
[`https.secureOptions`](https://redirect.github.com/sindresorhus/got/blob/599ae74e9f2a002eade81a0ec1722cf7dc28a9cd/documentation/5-https.md?plain=1#L136)
option
[`7ec1714`](https://redirect.github.com/sindresorhus/got/commit/7ec1714)
- Add
[`copyPipedHeaders`](https://redirect.github.com/sindresorhus/got/blob/599ae74e9f2a002eade81a0ec1722cf7dc28a9cd/documentation/2-options.md?plain=1#L526)
option to control automatic header copying from piped streams
[`d83dadd`](https://redirect.github.com/sindresorhus/got/commit/d83dadd)
- Add
[`stream.isReadonly`](https://redirect.github.com/sindresorhus/got/blob/599ae74e9f2a002eade81a0ec1722cf7dc28a9cd/documentation/3-streams.md?plain=1#L172)
property to detect read-only streams
[`030dfbb`](https://redirect.github.com/sindresorhus/got/commit/030dfbb)

##### Fixes

- Fix HTTP/2 timings NaN issue
[`398c11a`](https://redirect.github.com/sindresorhus/got/commit/398c11a)
- Fix shortcut methods ignoring handler errors
[`f004564`](https://redirect.github.com/sindresorhus/got/commit/f004564)
- Fix body reassignment in `beforeRetry` hooks
[`bf84d36`](https://redirect.github.com/sindresorhus/got/commit/bf84d36)
- Fix `beforeError` hook not being called for `ERR_UNSUPPORTED_PROTOCOL`
error
[`fb86418`](https://redirect.github.com/sindresorhus/got/commit/fb86418)
- FIx preserving `prefixUrl` in hooks
[`9725fbd`](https://redirect.github.com/sindresorhus/got/commit/9725fbd)
- Fix race condition causing retry after promise settles
[`1e49781`](https://redirect.github.com/sindresorhus/got/commit/1e49781)
- Fix stream validation errors causing unhandled rejections
[`2527bf6`](https://redirect.github.com/sindresorhus/got/commit/2527bf6)
- Fix incorrect `content-length` when piping decompressed responses
[`30b3b79`](https://redirect.github.com/sindresorhus/got/commit/30b3b79)
- Fix EPIPE errors bypassing retry logic in Promise API
[`6ae3e7f`](https://redirect.github.com/sindresorhus/got/commit/6ae3e7f)
- Fix silent hang when returning cached response with FormData body from
beforeRequest hook
[`e09a9bd`](https://redirect.github.com/sindresorhus/got/commit/e09a9bd)
- Fix hook type definitions to reflect normalized runtime state
[`6a544a3`](https://redirect.github.com/sindresorhus/got/commit/6a544a3)
- Fix `afterResponse` hook validation to allow `null` body values
[`60a4419`](https://redirect.github.com/sindresorhus/got/commit/60a4419)
- Fix DNS timing being non-zero when connecting to IP addresses
[`3d66aec`](https://redirect.github.com/sindresorhus/got/commit/3d66aec)
- Fix `timings.end` being undefined when stream is destroyed before
completion
[`4e75679`](https://redirect.github.com/sindresorhus/got/commit/4e75679)
- Fix properly treating different UNIX socket paths as different origins
[`e5659d4`](https://redirect.github.com/sindresorhus/got/commit/e5659d4)

##### Meta

I managed to get it almost down to zero issues! 🎉

***

###
[`v14.5.0`](https://redirect.github.com/sindresorhus/got/releases/tag/v14.5.0)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v14.4.9...v14.5.0)

- Add `retry.enforceRetryRules` option to fix statusCodes/limit
bypassing
[`7c0aee6`](https://redirect.github.com/sindresorhus/got/commit/7c0aee6)
- Add support for `serverName` HTTPS option
[`cdaab63`](https://redirect.github.com/sindresorhus/got/commit/cdaab63)
- Add `preserveHooks` option for `retryWithMergedOptions`
[`1abeba4`](https://redirect.github.com/sindresorhus/got/commit/1abeba4)
- Support `Iterable` and `AsyncIterable` as request body
[`b65b0e1`](https://redirect.github.com/sindresorhus/got/commit/b65b0e1)
- Fix hang on revalidated cached responses
[`2ab94fd`](https://redirect.github.com/sindresorhus/got/commit/2ab94fd)
- Fix handling of FormData getLength errors
[`a2812de`](https://redirect.github.com/sindresorhus/got/commit/a2812de)
- Fix `downloadProgress` firing for redirect responses
[`9ec6ff0`](https://redirect.github.com/sindresorhus/got/commit/9ec6ff0)
- Fix TypeScript type definition for retry event's createRetryStream
parameter
[`e899c07`](https://redirect.github.com/sindresorhus/got/commit/e899c07)
- Fix validation to accept `false` as agent value
[`6961284`](https://redirect.github.com/sindresorhus/got/commit/6961284)
- Fix HTTP/2 memory leak from timeout listeners with connection reuse
[`d1d4ed2`](https://redirect.github.com/sindresorhus/got/commit/d1d4ed2)
- Fix QuickLRU v7+ compatibility
[`23d0b6b`](https://redirect.github.com/sindresorhus/got/commit/23d0b6b)
- Fix it not using HTTP/2 connection reuse by default
[`724d592`](https://redirect.github.com/sindresorhus/got/commit/724d592)
- Fix hang with stream requests without body for methods like OPTIONS
[`dc4f1e3`](https://redirect.github.com/sindresorhus/got/commit/dc4f1e3)

***

###
[`v14.4.9`](https://redirect.github.com/sindresorhus/got/releases/tag/v14.4.9)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v14.4.8...v14.4.9)

- Fix hang with responses containing `content-encoding` headers but no
body
[`cc434bc`](https://redirect.github.com/sindresorhus/got/commit/cc434bc)

***

###
[`v14.4.8`](https://redirect.github.com/sindresorhus/got/releases/tag/v14.4.8)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v14.4.7...v14.4.8)

- Fix infinite loop when retrying with `request.options` in
`afterResponse` hook
[`dad6a91`](https://redirect.github.com/sindresorhus/got/commit/dad6a91)

***

###
[`v14.4.7`](https://redirect.github.com/sindresorhus/got/releases/tag/v14.4.7)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v14.4.6...v14.4.7)

- Fix: Gracefully handle undefined request
([#&#8203;2404](https://redirect.github.com/sindresorhus/got/issues/2404))
[`06029e0`](https://redirect.github.com/sindresorhus/got/commit/06029e0)

***

###
[`v14.4.6`](https://redirect.github.com/sindresorhus/got/releases/tag/v14.4.6)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v14.4.5...v14.4.6)

- Fix timeout error firing even though it's cancelled
([#&#8203;2399](https://redirect.github.com/sindresorhus/got/issues/2399))
[`7a92064`](https://redirect.github.com/sindresorhus/got/commit/7a92064)

###
[`v14.4.5`](https://redirect.github.com/sindresorhus/got/releases/tag/v14.4.5)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v14.4.4...v14.4.5)

- Fix a crash with Got accessing a non-existent request
([#&#8203;2391](https://redirect.github.com/sindresorhus/got/issues/2391))
[`c079b93`](https://redirect.github.com/sindresorhus/got/commit/c079b93)

###
[`v14.4.4`](https://redirect.github.com/sindresorhus/got/releases/tag/v14.4.4)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v14.4.3...v14.4.4)

- Fix support for `AbortSignal#timeout()`
([#&#8203;2388](https://redirect.github.com/sindresorhus/got/issues/2388))
[`92b378e`](https://redirect.github.com/sindresorhus/got/commit/92b378e)

###
[`v14.4.3`](https://redirect.github.com/sindresorhus/got/releases/tag/v14.4.3)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v14.4.2...v14.4.3)

- Fix cache with HTTP2
([#&#8203;2380](https://redirect.github.com/sindresorhus/got/issues/2380))
[`f2f8cb2`](https://redirect.github.com/sindresorhus/got/commit/f2f8cb2)

###
[`v14.4.2`](https://redirect.github.com/sindresorhus/got/releases/tag/v14.4.2)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v14.4.1...v14.4.2)

- Fix handling of invalid arguments
([#&#8203;2367](https://redirect.github.com/sindresorhus/got/issues/2367))
[`f44ef43`](https://redirect.github.com/sindresorhus/got/commit/f44ef43)

###
[`v14.4.1`](https://redirect.github.com/sindresorhus/got/releases/tag/v14.4.1)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v14.4.0...v14.4.1)

- Fix missing dependency
[`dfc54d9`](https://redirect.github.com/sindresorhus/got/commit/dfc54d9)

###
[`v14.4.0`](https://redirect.github.com/sindresorhus/got/releases/tag/v14.4.0)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v14.3.0...v14.4.0)

- Improve TypeScript types with generic extend
([#&#8203;2353](https://redirect.github.com/sindresorhus/got/issues/2353))
[`15ca4a0`](https://redirect.github.com/sindresorhus/got/commit/15ca4a0)

###
[`v14.3.0`](https://redirect.github.com/sindresorhus/got/releases/tag/v14.3.0)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v14.2.1...v14.3.0)

- Update dependencies
[`dbab6c3`](https://redirect.github.com/sindresorhus/got/commit/dbab6c3)

###
[`v14.2.1`](https://redirect.github.com/sindresorhus/got/releases/tag/v14.2.1)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v14.2.0...v14.2.1)

- Fix error handling when UTF-8 decoding fails
([#&#8203;2336](https://redirect.github.com/sindresorhus/got/issues/2336))
[`c81a611`](https://redirect.github.com/sindresorhus/got/commit/c81a611)

###
[`v14.2.0`](https://redirect.github.com/sindresorhus/got/releases/tag/v14.2.0)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v14.1.0...v14.2.0)

- Add `cause` property with the original error to `RequestError`
([#&#8203;2327](https://redirect.github.com/sindresorhus/got/issues/2327))
[`4cbd01d`](https://redirect.github.com/sindresorhus/got/commit/4cbd01d)

###
[`v14.1.0`](https://redirect.github.com/sindresorhus/got/releases/tag/v14.1.0)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v14.0.0...v14.1.0)

- Allow typing the body of a `RequestError` response
([#&#8203;2325](https://redirect.github.com/sindresorhus/got/issues/2325))
[`5e4f6ff`](https://redirect.github.com/sindresorhus/got/commit/5e4f6ff)

###
[`v14.0.0`](https://redirect.github.com/sindresorhus/got/releases/tag/v14.0.0)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v13.0.0...v14.0.0)

##### Breaking

- Require Node.js 20
([#&#8203;2313](https://redirect.github.com/sindresorhus/got/issues/2313))
[`a004263`](https://redirect.github.com/sindresorhus/got/commit/a004263)
- Why not target the oldest active Node.js LTS, which is Node.js 18? I
usually strictly follow this convention in my packages. However, this
package is the exception because the HTTP part of Node.js is
consistently buggy, and I don't have time to work around issues in older
Node.js releases. I you need to still support Node.js 18, I suggest
staying on Got v13, which is quite stable. Node.js 18 will be out of
active LTS in 5 months.

##### Improvements

- Make `followRedirect` option accept a function
([#&#8203;2306](https://redirect.github.com/sindresorhus/got/issues/2306))
[`7c3f147`](https://redirect.github.com/sindresorhus/got/commit/7c3f147)

###
[`v13.0.0`](https://redirect.github.com/sindresorhus/got/releases/tag/v13.0.0)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v12.6.1...v13.0.0)

As a reminder, Got continues to require ESM. For TypeScript users, this
includes having [`"module": "node16", "moduleResolution": "node16"` in
your
tsconfig](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c#how-can-i-make-my-typescript-project-output-esm).

##### Breaking

- Require Node.js 16
[`52a1063`](https://redirect.github.com/sindresorhus/got/commit/52a1063)
- Change the
[`enableUnixSockets`](https://redirect.github.com/sindresorhus/got/blob/main/documentation/2-options.md#enableunixsockets)
option to be `false` by default
[`852c312`](https://redirect.github.com/sindresorhus/got/commit/852c312)
  - Most users don't need it.

##### Improvements

- Allow specifying `undefined` for options
([#&#8203;2258](https://redirect.github.com/sindresorhus/got/issues/2258))
[`1cefe8b`](https://redirect.github.com/sindresorhus/got/commit/1cefe8b)

###
[`v12.6.1`](https://redirect.github.com/sindresorhus/got/releases/tag/v12.6.1)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v12.6.0...v12.6.1)

- Fix `get-stream` import statement
([#&#8203;2266](https://redirect.github.com/sindresorhus/got/issues/2266))
[`67d5039`](https://redirect.github.com/sindresorhus/got/commit/67d5039)

###
[`v12.6.0`](https://redirect.github.com/sindresorhus/got/releases/tag/v12.6.0)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v12.5.3...v12.6.0)

- Update dependencies
[`88c88fb`](https://redirect.github.com/sindresorhus/got/commit/88c88fb)
[`979272e`](https://redirect.github.com/sindresorhus/got/commit/979272e)
- Loosen URL validation strictness
([#&#8203;2200](https://redirect.github.com/sindresorhus/got/issues/2200))
[`0ca0b7f`](https://redirect.github.com/sindresorhus/got/commit/0ca0b7f)

###
[`v12.5.3`](https://redirect.github.com/sindresorhus/got/releases/tag/v12.5.3)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v12.5.2...v12.5.3)

- Fix abort event listeners not always being cleaned up
([#&#8203;2162](https://redirect.github.com/sindresorhus/got/issues/2162))
[`3cc40b5`](https://redirect.github.com/sindresorhus/got/commit/3cc40b5)

###
[`v12.5.2`](https://redirect.github.com/sindresorhus/got/releases/tag/v12.5.2)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v12.5.1...v12.5.2)

- Improve TypeScript 4.9 compatibility
([#&#8203;2163](https://redirect.github.com/sindresorhus/got/issues/2163))
[`39f83b6`](https://redirect.github.com/sindresorhus/got/commit/39f83b6)

###
[`v12.5.1`](https://redirect.github.com/sindresorhus/got/releases/tag/v12.5.1)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v12.5.0...v12.5.1)

- Fix compatibility with TypeScript and ESM
[`3b3ea67`](https://redirect.github.com/sindresorhus/got/commit/3b3ea67)
- Fix request body not being properly cached
([#&#8203;2150](https://redirect.github.com/sindresorhus/got/issues/2150))
[`3e9d3af`](https://redirect.github.com/sindresorhus/got/commit/3e9d3af)

###
[`v12.5.0`](https://redirect.github.com/sindresorhus/got/releases/tag/v12.5.0)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v12.4.1...v12.5.0)

- Disable method rewriting on 307 and 308 status codes
([#&#8203;2145](https://redirect.github.com/sindresorhus/got/issues/2145))
[`e049e94`](https://redirect.github.com/sindresorhus/got/commit/e049e94)
- Upgrade dependencies
[`8630815`](https://redirect.github.com/sindresorhus/got/commit/8630815)
[`f0ac0b3`](https://redirect.github.com/sindresorhus/got/commit/f0ac0b3)
[`4c3762a`](https://redirect.github.com/sindresorhus/got/commit/4c3762a)

###
[`v12.4.1`](https://redirect.github.com/sindresorhus/got/releases/tag/v12.4.1)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v12.4.0...v12.4.1)

##### Fixes

- Fix `options.context` being not extensible
[`b671480`](https://redirect.github.com/sindresorhus/got/commit/b671480715dbbff908e9a385f5e714570c663cd7)
- Don't emit `uploadProgress` after promise cancelation
[`693de21`](https://redirect.github.com/sindresorhus/got/commit/693de217b030816f574d6e4cb505ee2e77b21c29)

###
[`v12.4.0`](https://redirect.github.com/sindresorhus/got/releases/tag/v12.4.0)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v12.3.1...v12.4.0)

##### Improvements

- Support FormData without known length
([#&#8203;2120](https://redirect.github.com/sindresorhus/got/issues/2120))
[`850773c`](https://redirect.github.com/sindresorhus/got/commit/850773c)

##### Fixes

- Don't call `beforeError` hooks with `HTTPError` if the
`throwHttpErrors` option is `false`
([#&#8203;2104](https://redirect.github.com/sindresorhus/got/issues/2104))
[`3927348`](https://redirect.github.com/sindresorhus/got/commit/3927348)

###
[`v12.3.1`](https://redirect.github.com/sindresorhus/got/releases/tag/v12.3.1)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v12.3.0...v12.3.1)

- Don't freeze signal when freezing Options
([#&#8203;2100](https://redirect.github.com/sindresorhus/got/issues/2100))
[`43b1467`](https://redirect.github.com/sindresorhus/got/commit/43b1467)

###
[`v12.3.0`](https://redirect.github.com/sindresorhus/got/releases/tag/v12.3.0)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v12.2.0...v12.3.0)

- Add `.off()` method for events
([#&#8203;2092](https://redirect.github.com/sindresorhus/got/issues/2092))
[`88056be`](https://redirect.github.com/sindresorhus/got/commit/88056be)

###
[`v12.2.0`](https://redirect.github.com/sindresorhus/got/releases/tag/v12.2.0)

[Compare
Source](https://redirect.github.com/sindresorhus/got/compare/v12.1.0...v12.2.0)

- [Support
`AbortController`](https://redirect.github.com/sindresorhus/got/blob/main/documentation/2-options.md#signal)
([#&#8203;2020](https://redirect.github.com/sindresorhus/got/issues/2020))
[`6a6d2a9`](https://redirect.github.com/sindresorhus/got/commit/6a6d2a9)
- Add [`enableUnixSockets`](https://redirect.github.com/sindr

> [!IMPORTANT]
> ✂ PR body was truncated to here.


</details>

---

### Configuration

📅 **Schedule**: (UTC)

- Branch creation
  - At any time (no schedule defined)
- Automerge
  - At any time (no schedule defined)

🚦 **Automerge**: Disabled by config. Please merge this manually once you
are satisfied.

♻ **Rebasing**: Whenever PR is behind base branch, or you tick the
rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update
again.

---

- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check
this box

---

This PR was generated by [Mend Renovate](https://mend.io/renovate/).
View the [repository job
log](https://developer.mend.io/github/mlx-node/mlx-node).

<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0NC4yMjAuMCIsInVwZGF0ZWRJblZlciI6IjQ0LjIyOC4wIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6W119-->

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
…eces and q offset views (#380)

Follow-up to #377. Fixes the Codex findings on #377 and the gaps found
while fixing them.

```
host short of spare memory (7 GB runner): #374 governor refuses Optional claims
  GDN ladder rung refused ──► #377: kept for the turn's cold sidecar capture
                             this PR: at most TWO held rungs per scheduled sequence — the deepest, and the
                                      deepest within the reach this turn's K/V capture walk can get —
                                      cleared at that sequence's turn end; MoE gets the same fix
GPU without MPP prefill pipelines ──► portable varlen prefill
  bf16 rows in pieces ──► each piece is evaluated before the next (workspaces no longer overlap)
  piece = q view at an offset ──► paged reads accept a q view at a whole-head offset (all callers)
```

## Changes
- `qwen3_5` / `qwen3_5_moe` `gdn_prefix.rs`: a refused rung is held in
`gdn_unclaimed_rungs: HashMap<Option<SeqId>, Vec<_>>` (key =
`active_scheduled_seq`, `None` = serial lane). `hold_refused_rung` keeps
at most two per key: the deepest, and the deepest at or below the
predicted capture reach. The reach comes from
`ColdTierWalk::capture_reach`, which probes the same K/V chain keys and
per-turn block budget as `capture_chain` (blocks already on disk are
free); with no cold tier only the deepest is held. The capture reads
only the finishing sequence's rung; its turn end removes only that
entry; `release_scheduled_recurrent_for(seq)` drops a vacated sequence's
rung; `clear_reuse_state` drops all. The bound is two extra rungs per
live sequence (was: every refused rung of the ladder, held through
decode, outside reclaim). Deepest-only failed the e2e on the runner: the
harness captures 12 blocks per turn, so the reach (192–768 tokens) was
below the deepest rung (1248) and no sidecar was written.
- MoE: a refused rung was dropped, so no MoE rung reached the cold tier
on such a host; it now follows the dense rule.
- `paged_kv_cache_adapter.rs` `portable_prefill_attention`: every bf16
piece but the last is evaluated before the next is built. Measured on 16
pieces: peak growth 293.7 MB → 34.3 MB (one piece's partials 17.0 MB).
- `mlx_paged_ops.cpp`: `PagedAttention`, `PagedAttentionVarlen` and
`PagedPrefillAttention` accept a row-contiguous `q` at a non-zero offset
that is a whole number of heads. Every kernel binds `q` through
`CommandEncoder::set_input_array`, which adds `a.offset()`; no host code
does pointer math on `q`. Pools, scales, block tables, seq lens,
cu_seqlens and workspace keep the zero-offset rule. A copy in the FFI
could not work: the alias appears only inside `Contiguous::eval_gpu`.

## Tests
- `qwen3_5_cold_tier_restart_parity` under a local runner simulation
(portable prefill, 5,010,305,024 B working set, 7 GiB host with 2.5 GiB
spare): FAIL before this fix (`boundary_skips=2`, anchored at 0, as CI
run 43378257889), PASS after (cached 64 / 304 / 304, `installed=2`,
anchored at 304), PASS without the simulation.
- `a_refused_rung_within_the_capture_reach_reaches_the_cold_tier` (+ MoE
twin), `a_rung_refused_ram_still_reaches_the_cold_tier`,
`moe_rung_refused_ram_still_reaches_the_cold_tier`,
`overlapped_sequences_each_send_their_refused_rung_to_the_cold_tier` (+
MoE twin),
`portable_prefill_pieces_do_not_hold_their_partials_together`,
`portable_verify_pieces_at_long_context_attend` (8 rows at 131,072
tokens, piece 2 at offset 14,336), `paged_q_offset_view` (decode v1/v2,
varlen v1/v2, int8 tiled, MPP prefill, off-head-boundary refusal).
- One mutation per defect, each red when on and green when off, then
removed: f1, f2, f3 (now q_offset), f4, H1, q_align, deepest-only.
- `cargo +1.100.0 clippy --workspace --all-targets` with warnings
denied: clean. Touched modules' tests green.

## Not in this PR
- The scheduler sets `active_cache_owner_id` only at admission, so an
overlapped sequence's capture can filter by the wrong owner. S13
replaces this capture path.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
…ts (#381)

`lfm2_paged_vs_flat_greedy_token_parity` failed once on the CI VM (run
43384271735, PR #380) and passed on rerun of the same commit:

```
prompt #1 "What is 2 + 3? Answer with just the number."
  FLAT  (32 tokens) "The sum of 2 and 3 is"
  PAGED (32 tokens) ""
```

A bisect under a local runner simulation could not reproduce it (main →
#380 head: 9/9, byte-identical output; 12/12 under a two-process
stress), and #380's code does not reach LFM2 (instrumented: 0 portable
prefill calls, all 16,001 `q` checks at offset 0). The failing VM run
was 2–6× slower than its siblings from the bridge test on.

The panic message could not tell the two candidate causes apart:
- NaN logits collapsing to the pad token (a real defect),
- a thinking block that never closed within 32 tokens (a near-tie on the
VM's numerics).

It now prints, for both paths: `raw_text`, `thinking`,
`reasoning_tokens`, `prompt_tokens`, `cached_tokens`. Test-only change.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <[email protected]>
…nload, persist cache on by default

The inference process records each dispatched turn and samples its own
state to files under ~/.mlx-node/metrics. All fields are metadata
(numbers, small enums, identifiers).

- turn trace gains prefillMs / prefillTokens; streamed /v1/messages
  usage gains prefill_ms / prefill_tokens
- runtime sampler writes live-<pid>.json and daily runtime traces
- POST /v1/models/unload (409 while a turn, a load or a lease is active)
- a dropped model forces one V8 collection
- count_tokens skips the model-load gate for a resident model
- the paged KV disk cache is on by default for `mlx agent` and the
  desktop engine (flag > env > entry default), with whole-prompt
  capture; `--persist-cache`, `--no-persist-cache`,
  `--persist-whole-prompt` on `mlx serve`; the host drains the write
  queue on close
- engine policy env for the desktop engine
- lm: a GGUF model is named by its stem and listed with its
  quantization variants; qwen4_exp samples at 1.0 / 0.95 / 20

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Window policy, broker and sidecar changes that the new Control Panel
needs: the folder dialog for Work, the endpoint file fields, the
packaging of the bundled skills, the persist cache default and the
engine policy env of the sidecar.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
… providers

Redesign of the Control Panel SPA on the free Arc (uiarc.dev, MIT)
components plus own components, with more charts and detail pages:
Overview, Models, Sessions (Agent timeline), Metrics, Engine, Cache.

Chat/Work: the Control Panel process runs mlx-agent over ACP. Chat has
the app web tools only (no shell). Work runs in a folder the user picks,
behind permission cards, with a permission mode per conversation:
Ask, Auto (allow-only command gate; known commands and edits in the
Work folder and in folders the user owns under /tmp) and Bypass (allow
every request). A Work turn has no time limit.

Web Search: Exa / DeepSeek / Brave / Firecrawl keys in the macOS
Keychain, one search provider selected, pinned provider skills bundled.

A dotted orb (MIT thinking-orbs subset) shows while a turn waits.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
… on a partial store, a follow-up turn reuses its prefix

Tool calls: the GGUF tokenizer marked <tool_call>, </tool_call>, <think>
and </think> as special, so every output decode dropped them and the
parsers never saw a call. Only CONTROL rows are special now (the Splash
rule); the asset cache identity is bumped and the load checks that the
tags survive a decode.

Prefill: on a partial expert store the window fell to 1 token (about
10 tok/s). It is a fixed 1,024 rows; a store the load gate refused
halves a pass only when its scratch is larger than the gate reserved.
The device-route cooldown is per request. residencyInfo gains
slotHits, slotMisses, checkpointBytesRead and routeReplays.

Prefix reuse: a turn stores the state outside the KV pool at pass
borders (a replay point and a checkpoint each 4,096 rows) and registers
the KV blocks below it; a later turn restores the deepest matching
state and prefills only the rest. Block keys carry their whole pass, so
two conversations share a block only when they ran the same pass.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…chine's memory

Qwen3.5 dense and MoE run on the continuous-batching scheduler with no
env variable; MLX_SERVE_FORCE_SERIAL=1 is the only rollback, and
MLX_CONTINUOUS_BATCHING is gone (the desktop engine policy no longer
sets it).

- The memory plan computes the lane count at load: plan one lane, then
  grant the most lanes whose cost keeps that window. The ceiling is 4,
  and 8 on a machine with 256 GB of physical memory or more. Lanes give
  way before the context window. The granted count sets the recurrent
  state table width, the scheduler capacity, admission and
  maxConcurrentSequences().
- The MTP state is charged once in the memory plan; a speculative turn
  may fill the max pool on the ledger path (it was refused below the
  planned window).
- The batched decode loop submits each layer as the single-row path
  does.
- A MoE decode row prices its expert work.
- MTP norms: one shift decision for the whole MTP module from four
  norms. The 0.8B checkpoint read as shifted (mean 0.5052) and its MTP
  head accepted no draft.
- Tests that share the process-wide memory governor run in their own
  process.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@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: 81e23d4a-5df9-480c-8544-6c15758f9225

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-13T13:50:17.067068Z fd2a568 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.

Brooooooklyn and others added 8 commits November 13, 2026 18:12
…olumn

The orb and the status dot now use one 20 px leading column, so the title
and the model name start at the same x in every state of the card.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
The qwen3-generate-batch load hook used the 10 s default and timed out on
a slow CI runner (12.5 s); the test timeout was already 120 s.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…rebuilt

A local model can write a wrapper tool call flat: use_tool with tool_name
and url side by side, where the schema wants url inside tool_input. The
agent refuses that form before any permission request, so the web fetch
never ran. The Messages endpoint now moves the undeclared keys into the
one missing required object property, only when the schema has no union,
its root admits no extra keys, and no other tool shares the name. Text
arguments are never touched, and the agent's arguments-file form passes
unchanged.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…; the composer row never clips Send

A new Work conversation can raise its permission mode before the first
message, with the same confirm steps. The Control Panel holds the pick in
memory against a draft id and the checked folder; the first message
carries only that id, and the mode's history line is written before the
first turn starts. A move down during the start reaches the draft that
was sent.

The Send button has its own column. Each part of the key legend is drawn
whole or not at all, and it gives way first, then the folder and web
labels, then the quantization badge, then the model name.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
… booked; convert shares the MTP norm rule

Scheduled MTP on MoE verified all owners in one forward, so a lane's
tokens changed with the number of lanes. The verify now runs once per
owner; AR decode stays fused. The real-model wave test compares each MTP
lane with the same prompt scheduled alone.

On a load with the disk cache on, the lane price in the memory plan now
includes the refused GDN rungs a sequence may hold, and admission reserves
them after the grant without a wait: with no room the turn runs and keeps
no refused rung.

mlx convert decides the MTP norm shift with the loader's rule.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…shows the kernel warm-up

A turn record, the live file and the progress ping gain waitMs (dispatch
to pickup), slotMs and prepareMs, with the phases slot and prepare. The
page says 'Waiting, model busy' while the model thread runs another
step, 'Waiting for a slot' only for a real lane wait, and 'Preparing'
while a cached prefix is restored. Setup time no longer counts slot and
prepare time twice.

The live file (v2) lists every load in progress with its phase and step
count, and the load card shows 'Preparing GPU kernels, n of m'. All new
native fields are read as not known when an addon does not send them.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…r a restore, and restores after a restart

Prefill passes now also end at the block before each assistant message, so
a warm turn reuses its prefix up to the block before the previous turn's
generation prompt instead of the last 1,024 grid line, and its output at
temperature 0 still equals a cold prefill of the same prompt. A turn
restored from a prefix state carries the draft history, so an MTP load
drafts on it.

Prefix states and the KV blocks they need are written behind the turn to
the paged disk cache (same switch: on by default for mlx agent and the
desktop engine) and restored after an engine restart. Files are written
to a temp name and renamed, carry a checksum and the checkpoint identity,
and a truncated, foreign or orphaned file is refused and removed. The
memory plan books the staging copies.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…continues once after a length stop

The desktop engine and the server that mlx agent starts now set a
thinking budget of 12,000 tokens, the cycle guard and the thinking end
text for Messages requests that set no budget of their own. mlx serve by
hand keeps no cap; it gains --thinking-cycle-guard and
--thinking-end-text. The turn record gains the budget, its source, the
output cap and the engine's reasoning outcome.

The app's output cap is answer room plus the budget (Work 28,384, Chat
20,192). After a length stop in Work the app waits for the agent's own
end line and sends one visible continue; a second length stop in a row
with no tool call between ends the turn and says so. No timer ends or
continues a turn.

A thought shows its time only when the app saw it live; a thought read
from disk shows none, because the agent keeps one time stamp for it.

Co-Authored-By: Claude Fable 5.2 <[email protected]>

@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: 6c78288d08

ℹ️ 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 packages/dashboard/package.json Resolved
Staging copied only dist and web of a workspace package, so a packaged
app had no dashboard skills folder and Chat stopped with
skill-bundle-corrupt. The copy now follows the package's own files list
(without src, which only the source export condition uses), and refuses
a package with no list or with an entry that is not a plain top-level
name. A test stages the real dashboard list and runs the dashboard's own
bundle check on the copy.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@Brooooooklyn
Brooooooklyn changed the base branch from main to codex/issue-142-gemma4-benchmark November 15, 2026 02:07
Brooooooklyn added a commit that referenced this pull request Nov 15, 2026
…heduler on by default (#384)

## Summary

One branch with 23 commits, on `main` after #378 (the DFlash2 state disk
tier) and #383. Replaces #382 (closed).

| Area | What |
|---|---|
| `packages/server` | Turn traces and runtime samples (metadata only),
measured prefill (`prefillMs` / `prefillTokens`), `POST
/v1/models/unload`, GGUF model naming with quantization variants, a turn
reports where it waits (`queued / slot / prepare / prefill / decode`), a
tool call that misses its one object argument gets it rebuilt, a
thinking budget with a cycle guard and an end text on the agent hosts, a
reload of the same model closes the old model's state cache first |
| `packages/desktop` | Control Panel host changes: folder dialog for
Work, endpoint file fields, bundled skills. MAIN judges Control Panel
liveness by ping; a slow page call no longer restarts the Control Panel
|
| `packages/dashboard` | Control Panel redesign on the free Arc
components (MIT) plus own components; Chat / Work over ACP; permission
modes Ask / Auto / Bypass; Web Search providers (keys in the macOS
Keychain); Agent timeline; waiting orb; load card with the kernel
warm-up; a Work turn continues once after a length stop; the Cache page
lists the model caches under `prefix-cache/` and can delete an idle one
|
| `qwen4_exp` | Flash Next: tool calls parse (tokenizer special flags),
the prefill window stays 1,024 rows on a partial expert store, a
follow-up turn reuses its prefix to a message boundary, drafts after a
restore. Its stored states live in a per-model SSD tier as fixed-span
state records and are taken back at load |
| `qwen3_5` | The scheduler is on by default for Qwen3.5 dense and MoE
with no env; the lane count comes from the memory plan (up to 4, up to 8
from 256 GB); MoE MTP lanes keep their lone tokens; MTP norm shift rule;
`stateTierNamespace()` |
| `engine` | Thinking cycle guard and end text; the thinking cut is a
row of a full-depth speculative verify; load-time warm-up of the
scheduler's pipelines with start-class memory claims; stream progress
phases and wait timers; the paged-attention metallib loads from memory
(no temp file) |

## Behaviour changes

- `MLX_CONTINUOUS_BATCHING` is gone. `MLX_SERVE_FORCE_SERIAL=1` is the
one rollback.
- Qwen3.5 lanes: plan one lane, then grant the most lanes that keep that
context window. Lanes give way before the window. The lane table is
pinned with the state tier off and on; with the tier on, one GDN cell of
staging moves five memory-bound rows (for example 9B AR at 16 GB: 2
lanes to 1).
- Qwen3.5 0.8B: the MTP norms were read as shifted and the MTP head
accepted no draft. One decision for the whole MTP module from four
norms. Only the 0.8B checkpoints change their decision.
- Load warm-up (Qwen3.5 dense / MoE loads that serve chat turns on the
scheduler):
- Scratch turns per lane count and row class run before the load serves.
The model state, the block pool and the state tier read as before, and
the model's governor books are put back.
- A warm-up claim is a Floor claim that tries once. A required step
(`MaxPrefill`, each row class, width 1, and the width-1 draft step on a
drafting model) that the engine limit refuses fails the load at once
with `memory plan: the load's warm-up (<step>) could not be allocated:
<cause>`; a host-pressure refusal runs the warm-up again every second
for up to 30 s, then fails the load. Before a start claim is refused,
MLX's free pool is cleared once. A KV block shortage still counts the
step as skipped.
  - `mlx eval`, FP8 calibration and CLEF loads run no warm-up.
- Thinking cut under speculation (MTP, DSpark, DFlash / DFlash2,
scheduled lanes): a cycle keeps its depth near the budget. The cut is
one row of the verify; rows from the cut take the end tokens, and end
tokens replace the first proposals once no thinking token is left.
Output equals plain decoding at T=0; tokens before the cut do not depend
on where the cut is. There is no seed on the chat API, so sampled output
is not repeatable (docs/vllm-speculative-alignment.md, X8).
- Disk cache: the desktop engine, `mlx agent` and `mlx serve` use the
mechanism of `main`. Qwen3.5 persists DFlash2 states in the per-model
state tier. The whole-prompt capture of this PR (`persistWholePrompt`,
on for the desktop engine and `mlx agent`) applies to the per-turn
families only (Qwen3, Gemma4, Muse-Glimmer, LFM2). The refused-rung
booking of an earlier head is dropped, because `main` deleted refused
rungs.
- A Qwen3.5 or Flash Next trace row carries `stateTier` (`persistent` /
`temp` / `off`); the Cache page counts such a turn by it. `coldEnabled`
keeps its meaning (the process tier).
- Flash Next: `<tool_call>`, `</tool_call>`, `<think>`, `</think>` are
no longer special tokens; the asset cache identity is bumped, so the
tokenizer sidecar is rebuilt once.
- Flash Next disk cache, now on the per-model tier
`~/.mlx-node/cache/prefix-cache/<ns>` (lock, quota, 14-day rule,
`--max-cache-disk`, `--cache-dir`, the persist switch, `closeCache`):
- Persistent by default on every host. A load with the switch off, with
no GGUF identity, or whose namespace another process holds for 20 s gets
a temporary tier; `--max-cache-disk 0` gets none.
- Only states of 2,048 tokens or more are written, 10 s after
publication, as one fixed-span record (format `qwen4-prefix-v3`; older
objects and objects under `paged/v1` are not read: one cold start). A
state is durable only when its whole KV and draft chain is on disk.
- States share the tier's one quota; a reopen under a lower limit trims
before the tier serves. At load a persistent tier adopts every whole
state as a disk-only entry that a turn reads back and promotes.
- `closeCache` resolves true only when every waiting state and queued
copy landed. After a failed state write the row reports the tier as off.
- Staging: one state plus the block queues (about 240 to 260 MiB) is set
aside on every load that opens a tier.
- Flash Next and Qwen3.5 share the root limit under `prefix-cache/`: a
load can remove another model's idle cache.
- Same-model reload in one engine (A → B → A): the host awaits the old
model's `closeCache` (up to 6 s) before the new load, so the new load
opens the persistent namespace instead of a temporary tier.
- Cache page: one panel per cache root (the configured root and each
running engine's `--cache-dir`). A folder is a model cache only when it
holds a regular `lock` file. Rows show size, files, last use and lock
state, and the model name when a running engine reports that namespace
(`stateNamespace` in the heartbeat). The walk is bounded by count and
time. Delete: confirmed at the button, only an idle cache, refused when
an engine holds the lock or opened the cache after the listing; the
directory is held open and re-checked before every unlink; steps leave a
300 ms gap for an engine's lock retry.
- New napi surface: `ChatConfig.thinkingCycleGuard` / `thinkingEndText`;
`reasoningClose` / `reasoningCutAt` / `reasoningCyclePeriod` /
`reasoningStrayCloses` on the result and the done chunk;
`ChatStreamProgress.phase` (6 values) with `waitMs` / `slotMs` /
`prepareMs`; `WarmupReport`, `LoadProgress`, `loadProgress(path)`,
`pipelineStats()`, the `warmup` getter; `Qwen4ExpModel.closeCache` /
`stateTierMode` (`persistent` / `temp` / `off`), `prefixDiskAdopted`,
`Qwen4ExpLoadOptions.cacheDisk` / `cacheDir`; `stateTierNamespace()` on
the Qwen3.5, Qwen3.5 MoE and Flash Next models.
- Control Panel recovery: the page can no longer ask for a restart; a
call with no reply fails alone with `E_TIMEOUT`. MAIN pings every 5 s
and restarts the panel after 30 s of silence (120 s when a turn runs). A
stuck database worker restarts alone. Each recovery writes metadata rows
to `~/.mlx-node/ledger/`.

## Test plan

- [x] `cargo test -p mlx-core --lib` (scoped: engine, model_thread,
tokenizer, tools, paged KV adapter, sampling, qwen3, qwen3_5, qwen4_exp,
gemma4, lfm2, nemotron_h, muse_glimmer, clef, memory_plan, disk_tier,
cold_tier, quality, calibration): `3064 passed; 0 failed; 119 ignored`
- [x] `cargo test -p mlx-paged-attn --lib`: `223 passed; 0 failed; 8
ignored`; `cargo test -p mlx-metal --lib`: `6 passed`
- [x] `cargo clippy -p mlx-core -p mlx-metal -p mlx-paged-attn
--all-targets -- -D warnings`, `cargo fmt --all -- --check`
- [x] `yarn build:native` (full profile), both `index.d.cts` copies in
sync
- [x] `yarn build:ts`, `yarn typecheck`, `vp lint --type-aware
--type-check` on the touched files, UI build, pack test
- [x] `vp test` (dashboard, server, desktop, agent, lm, cli,
`__test__/server`, `__test__/cli`): `Test Files 317 passed | 3 skipped`,
`Tests 7126 passed | 15 skipped`
- [x] Qwen3.5 0.8B, real weights, persistent state tier in a throwaway
cache dir, one process:
  - warm-up 56 steps, 0 skipped, on the first load and on the reload;
- T=0, thinking budget 64, no cached prefix: MTP off (80 decode batches
for 80 tokens), scheduled MTP (23 batches, 23 cycles), whole-turn
adaptive MTP (23 cycles); all close by `budget` at 64 with the end text;
thinking and answer equal across the three;
- a 5,691-token prompt, `closeCache` true, reload from the same cache
dir: 1 state adopted, the next turn restores 5,680 tokens from disk and
gives the same answer.
- [x] Flash Next (Qwen3.8 Flash Next UD-Q4_K_XL GGUF), real weights,
host defaults, throwaway home and cache dir, two processes:
- load: `stateTierMode` `persistent`, the namespace directory and its
`lock` exist;
- a 6,087-token turn (cold), a tool turn (`finishReason: tool_calls`,
one call with the right arguments), a follow-up turn that reuses 6,080
tokens from memory;
- the state is durable 10 s after publication (one 115.8 MB state record
plus its block chain); `closeCache` resolves true;
- reload: `prefixDiskAdopted` 1; the same follow-up turn restores 6,080
tokens from disk (`prefixDiskRestored` 1, first token after 353 ms) and
its answer is identical at T=0; one more follow-up turn; `closeCache`
true.
- [ ] Not run: the warm-up on real 27B / MoE geometry, MoE parity on a
real checkpoint, the Control Panel recovery on a real Electron process,
`__test__/cli/agent-e2e`

## Known limits

- MoE scheduled MTP with 2 or more lanes is not bit-exact against one
lane alone (batch-shape rounding). AR is exact.
- The first turn can still compile a pipeline that takes the prompt
length as a build-time constant (`qwen4_window_conv`,
`qwen4_gdn_prepare` under 64 rows).
- A load that came up with skipped warm-up steps can now fail when
memory is short (see the warm-up rule above).
- The first Flash Next turn after a load takes about 6 s to its first
token (also for a 19-token prompt); later turns do not.
- Flash Next state write: one 121.9 MiB state takes about 16 ms on the
model thread (two copy passes), once per stored state. On a temporary
tier the first state that memory drops is lost.
- A load that does not get its namespace lock within 20 s keeps a
temporary tier for its life. A Qwen3.5 `closeCache` waits behind a
running turn, so a same-model reload during a long turn can still land
there.
- `stateTierMode()` and `stateTierNamespace()` take the tier's hold
lock; the JS thread can wait for one remove (milliseconds).
- Cache page: a cache of a stopped engine shows its short hash (the tier
writes no model metadata); a `--cache-dir` root of a stopped engine is
not listed; an engine that runs only Flash Next reports no limit; the
delete keeps a microsecond window between its directory check and each
unlink (Node has no `unlinkat`), usable only by a process of the same
user.
- The Auto `/tmp` rule ships as built by owner decision.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01LJdkgMbCXHf4khtrZCVNPB

---------

Co-authored-by: Claude Fable 5.2 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants