Skip to content

feat(kv-int8): DFlash2 states spill to a disk tier and survive a restart - #378

Merged
Brooooooklyn merged 21 commits into
mainfrom
feat/kv-int8-s13-disk-state-tier
Nov 13, 2026
Merged

Brooooooklyn merged 21 commits into
mainfrom
feat/kv-int8-s13-disk-state-tier

Conversation

@Brooooooklyn

Copy link
Copy Markdown
Contributor

Stage S13 of the Splash int8 KV alignment (follows stack #344, now in main). Base: main.

This branch sits on #377 (main CI fix) and shows its 2 commits until #377 merges; then it is rebased onto main. Review only the last commit.

DFlash2 states (GDN cell + 4-bit draft window) now get an SSD tier, on by default like Splash. An evicted state is written to disk and read back on a later hit. With --persistent-cache the tier stays across restarts. Splash: StateCache disk copies, WriteBehind, SlotFile, openDiskTier, DiskSpace.

before:  evict state ──► gone (next turn re-prefills)
         qwen3_5 cold tier: off in serve; per-turn KV + GDN sidecar when on
after:   evict state ──► has disk copy?  yes ──► free RAM now
                                         no  ──► stage one write (NeedsWrite), free RAM now
         hit ──► RAM or disk (deepest) ──► read into lane ──► optional promotion
         tier: temp dir $TMPDIR/mlx-node-cache-*  (default, auto quota ≤ 32 GiB)
               <cache-dir>/<namespace> + flock    (--persistent-cache, adopted at load)
         stop: closeCache ──► one 6 s flush ──► temp dir removed

Changes

  • New disk_tier.rs: tier options, auto quota min(32 GiB, room / 4), a namespace from the target, draft and window, temp vs persistent, a held lock, stale namespace removal at every start (Splash CacheDirectory::removeStale).
  • cold_cache (mlx-paged-attn): a DFlash2State object with spans [cell, window], charged its file size (Splash slotBytesFor(payload)). A state lane goes before queued blocks. A non-space write failure stops tracked writes; ENOSPC / EDQUOT count as space errors.
  • Store entries hold RAM, disk or both, with one staging buffer and one write in flight. The memory plan sets the staging buffer aside (state_staging_bytes, Splash stateStagingBytes).
  • Ledger: Victim.later, uncopied runs and copy demand (60 s). An Immediate claim passes units that land later; a CanWait claim waits on a pending write.
  • Copy demand is Splash's first term: 2 × the pages the running lanes' next commands add beyond what they hold (next_command_pages, Tick::Full { command_pages }).
  • A disk state keeps its KV chain until the chain is on disk. A reclaim's chain goes before a copy ahead.
  • Write-behind (port of WriteBehind): ordinary points ≥ 2048 tokens due after 10 s; a persistent tier copies all, a temp tier only on copy demand; the state first, then its chain.
  • A refused capture goes to disk from the lane (Splash publishStateToDisk).
  • Restore takes the deepest RAM or disk state; the payload must equal the state size. A bad read discards the state and resumes lower. Promotion is Optional and Immediate. AR turns read disk states too.
  • Restart: adopt_all takes back states whose whole chain is on disk, after fitting the quota.
  • closeCache (napi, dense and MoE) flushes by a deadline. serve and mlx agent take --max-cache-disk, --persistent-cache and --cache-dir; the host closes every cache in one flush budget, and mlx agent stops serve after 15 s (supervision.ts).
  • /health memory_governor.dflash2_states gains the disk fields (entries, bytes, offloads, failures, promotions, publications, write-behind counts).

Memory plan

plan before after
27B int8 + DFlash2 window (unit-test estimate, tier Auto) 221,177 212,985
state staging – 159,842,304 B

The window drops 8,192 tokens: the staging buffer of one state is now fixed. With the tier off the window stays 221,177.

Deleted

  • --no-persist-cache, persistPagedCache (agent and override), qwen3_5 / MoE persist_paged_cache and their MLX_PERSIST_PAGED_CACHE reads.
  • The qwen3_5 per-turn KV and GDN cold sidecar path: ColdGroup::GdnState, the sidecar capture / install, ColdTierContext.sidecar_policy (now ColdContextBacking), qwen3_5 in COLD_RESTORE_FAMILIES, the qwen3_5 cold parity tests.
  • The GDN ladder retention (want_ladder, GdnRetentionPolicy Ladder, the same-owner victim search); 2 checkpoints per owner.
  • Ledger::uncopied_need_bytes, SHUTDOWN_TIMEOUT_MS, SERVE_STOP_GRACE_MS.

Tests

  • 58 named mutations, each red when on and green when off: 53 Rust runtime switches on one test binary, 5 TS source edits. Examples: state charged the read bound (K81), state lane behind blocks (SL1), auto quota ignores room (DQ1), held namespace not locked (PL1), staging left out of the plan (SG1), later ignored by Immediate (LT1), failed copy kept (WF1), chain mark dropped at landing (CM1), write-behind copies without demand (WB1), no disk arm on a refused capture (DP1), a bad read not discarded (BR1), adoption without the whole-chain check (AD1), flush that writes nothing (FL3), reclaim chain behind a copy ahead (CY1), held blocks not subtracted (CP1), stale namespaces kept on a temp open (SC1), no quota fit at adoption (FQ1), write failure not stopping the tier (WS1), full volume not refused (FS1), replaced lock file (NL1), host flush budget per model (HC1), agent drops --persistent-cache (TSF1).
  • cargo fmt --all -- --check, cargo clippy --workspace --all-targets -D warnings, yarn build:native (index.d.cts unchanged), yarn typecheck, yarn tsc -b --force, vp fmt --check and vp lint --type-aware --type-check on the touched TS files: clean.
  • RUST_TEST_THREADS=1: cargo test -p mlx-paged-attn (lib + tests) 337 passed, 0 failed; mlx-core --lib 4,829 passed, 0 failed, 218 ignored; cargo test --workspace --test '*' 281 passed, 0 failed, 191 ignored; the other crates' lib / bin tests 25 passed.
  • CI VM run (local switch, not committed: no Apple GPU family, paged prefill pipelines fail to build, 4,259,180,544 B working set; CI env): mlx-core --lib and --test '*' green after the skip below.
  • vp test on __test__/cli, __test__/server, packages/{agent,cli,dashboard,lm}/__test__, packages/server: 139 files, 2,936 tests passed, 8 skipped.

Rebase onto main

  • draft_context.rs: main added eval(), S13 added write_bytes / read_bytes; both kept. read_bytes now evaluates with eval_arrays_with_context, so a failed read is an error before the bounds move (main's rule for snapshot / copy_from).
  • dflash2_decode.rs tests: main's chunk_kv_is_booked_before_its_capture and S13's disk tests both kept. The 8 new disk tests that prefill on the pool take main's paged_prefill_unsupported skip (they failed only on the CI VM).
  • utils/functional.rs (fix: test precision (reranker f32, MoE autograd stop_gradient, deterministic draft parity) #348): its MoE test config named fields main no longer has (paged_cache_initial_memory_mb, use_block_paged_cache) plus persist_paged_cache, which S13 removes; it now lists main's fields (rope_scaling: None). This lib test target did not compile on main.
  • S13's deleted qwen3_5 cold parity tests and retention_sim.rs: main had not changed them.

Gaps

  • No per-leaf KV demotion; a disk state writes its chain after itself (S23).
  • One object file per state or block, not slot files; a crash leaves the temp dir until the next start (S23).
  • No write budget (--max-cache-disk-writes) (S23).
  • Disk recency is the object's last access; no relabel at stop (S23).
  • Restore reads run on the model thread (S24).
  • SHA-256 over every object, not CRC-32C per segment.
  • Host staging copies from MLX arrays on write and on read.
  • A qwen3_5 load without a DFlash2 draft has no SSD tier.
  • Each loaded model opens its own tier and writer thread.
  • Copy demand has no growth term; a whole DFlash2 turn adds nothing between commands (S15).
  • Old gdn_state objects in ~/.mlx-node/cache/paged/v1 are not indexed or removed, and a crash between mkdtemp and the rename leaves a .mlx-node-cache-new-* dir.
  • No probation and no clean-end record (S23).
  • During a long DFlash2 turn an owed chain moves only between commands (S24).
  • The R2 lock test checks named() directly; the R1 space check is tested with a large reserve, not a real full volume.

Not in this PR (live, not run)

  • L0 window and /health disk fields on the 27B GGUF, S vs S12; L1 restart survival with --persistent-cache (turn 2 reads the prefix back); L2 eviction writes under --max-memory 22G with the default temp tier, temp dir gone after stop; L3 decode speed S vs S12 (within 3%).

🤖 Generated with Claude Code

@Brooooooklyn Brooooooklyn added the model-e2e Run the heavy Model E2E workflow (per-family real-checkpoint tests) on this PR label Nov 12, 2026
@coderabbitai

coderabbitai Bot commented Nov 12, 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: 5aa9befd-5da3-46f8-a74d-98c4bea7dbea

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 12, 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:51:11.097844Z d8e954f 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.

@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: df71b3b4f7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread crates/mlx-core/src/disk_tier.rs Resolved

@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: f622e5340d

ℹ️ 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".

@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: 5d58e1c1e3

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Brooooooklyn and others added 16 commits November 13, 2026 19:12
Like Splash StateCache disk copies, WriteBehind and openDiskTier:
- an evicted DFlash2 state is written to an SSD tier (temp files by
  default, auto quota up to 32 GiB) and read back on a later hit;
- --persistent-cache keeps the tier across restarts under a locked
  cache dir; a clean stop flushes waiting writes (closeCache);
- copy-ahead and reclaim chains run from the governor tick, with the
  copy demand taken from the lanes' next commands;
- serve and agent take --max-cache-disk, --persistent-cache and
  --cache-dir; --no-persist-cache, the GDN ladder retention and the
  gdn_state cold group are deleted.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… idle siblings follow Splash

L1: a closed persistent tier hands its namespace lock to the writer, released only once the writer returns (Splash ~SlotFile joins before ~CacheDirectory unlocks)
W1: DraftContextWindow::read_bytes writes the disk bytes into the window it holds, no second window beside the admitted one (Splash stateSpans)
M1: the cold cache reports the DFlash2 state objects its evictions clear; poll_offload drops their disk copies and the disk-only states (Splash Cache::freeDiskSpace)
Q1: the tier keeps the root's idle siblings and DiskTier::measure, run at every Full tick, removes the oldest as the tier grows (Splash DiskSpace::measure)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
reclaim() erased a RAM-only state whose chain the tier cannot hold, but
model_units still listed it as needing a write, with no chain marks: a
need of blocks never reached it and a device need waited for a write
that never comes. Both now follow one rule, reclaim_writes() with
point_fits, as Splash Cache::stateReclaim and StateCache::reclaim both
follow StateCache::reclaimWrites.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The draft's files are snapshotted before `load_dflash2` and compared after
the namespace reads their identity, as the target's shards already are. A
change in between falls back to the temporary tier, so states fused with
the old draft never land under the replacement's namespace (Splash keys
target and draft by one verified record, `assembly.verify`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…he SSD tier

A dense or MoE paged load without a DFlash2 draft now opens the state
tier, and its plain text turns publish the restore points Splash does
(publishReachedStateBoundaries): a checkpoint every 4096 prompt tokens
and the replay point at the last whole block before the generation
prompt. A capture the ledger refuses goes to disk from the lane
(publishStateToDisk), the replay point waits behind (WriteBehind), and
after a restart Cache::adopt takes the states back and the prime resumes
at them (acquireDeepest, promotedCopy).

- the namespace, the state spans and the anchor carry no draft window
  on such a load ("draft none", one span: the GDN cell)
- the memory plan stages one GDN cell for a draftless pool load
- turn states are kept per scheduled sequence, so interleaved prefill
  slices keep their own points and cursors
- LaneStateSink and LanePrefill hook the prefill chunks of both families
- the turn engine hands the generation suffix to every paged backend
- closeCache is a plain async napi method, callable from Rust tests

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Real-weights gate on Qwen3.5-0.8B bf16: a persistent load publishes the
checkpoint and the replay point, closes cleanly, and the next load takes
them back; the follow-up turn resumes at the replay point and matches a
cold run token for token. The qwen3_5-dense CI leg runs it and, on the
7 GB VM where every optional claim is refused, also asserts the lane's
disk write and the resume at the checkpoint (MLX_E2E_EXPECT_LANE_DISK).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
mlx serve, mlx agent, mlx launch claude and the desktop engine host now
load qwen3_5 / qwen3_5_moe with a persistent state tier unless
--no-persistent-cache or --max-cache-disk 0 is given (Splash defaults to
a temporary cache; restart persistence is the point of the tier). The
host fills the default, so every host caller gets it; library loads keep
a temporary tier. --cache-dir no longer needs --persistent-cache, and
--persistent-cache beside --no-persistent-cache is a usage error. mlx
agent forwards --no-persistent-cache to the serve it spawns.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A native-MTP turn now reaches its Splash state boundaries and publishes
them exactly as a plain turn does (publishReachedStateBoundaries runs for
every request). Every official Qwen3.5 checkpoint carries MTP heads and
ChatSession turns MTP on for them, so before this a default `mlx serve`
conversation published nothing and prefilled cold after a restart.

- the planned-MTP whole-turn cores (sync and stream) prime through the
  same disk-state lookup as an autoregressive prime (the disk state's
  chain is armed with the KV lookup), open the lane's turn, prefill
  through LaneStateSink / LanePrefill, end the turn's points at finalize,
  and take the generation prompt that places the replay point
- the MTP prefill (`run_paged_prefill_chunk_with_hidden_with_size`) takes
  a PrefillTarget and tap sink: it books, captures and reaches points
  like the plain prefill while it keeps the drafter's hidden rows
- scheduled MTP sequences (dense and MoE) prefill through the lane sink
- a refused capture goes from the lane to disk, the replay point waits
  behind, and after a restart an MTP turn resumes from the disk state
- the restart gate runs the default product path: a streamed MTP turn as
  ChatSession sends it on the CI checkpoint, and a plain sync case; each
  restart's first turn is the one that resumes

Tests: an MTP turn publishes its plan and decodes the same tokens as a
turn that keeps no state (granted and refused-to-disk), an MTP restart
restores the disk state, scheduled dense and MoE MTP prefills publish.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… waits for the cache flush

Splash plans and publishes a request's state boundaries for every request
on a draft load (configureDraftStatePlan, publishReachedStateBoundaries),
each state with its draft window. An autoregressive whole turn on a
DFlash2 load (speculation off for the request) primed and prefilled plain,
kept its session live and published nothing.

- dense and MoE: on a draft load the plain prime and prefill hooks run the
  DFlash2 prime and tapped prefill (`draft_lane_turn`), so the turn's
  points carry the draft window and its lane is released at its end
- a suspended autoregressive lane on a draft load resumes from its deepest
  stored state and replays tapped, as a DFlash2 lane does
- draft-load tests that used an AR turn as the plain reference call the
  plain prime and prefill directly

The desktop INFERENCE supervisor sent SIGKILL 8 s after SIGTERM, while the
sidecar host spends up to SERVER_CLOSE_MS (5 s) closing HTTP and then up to
FLUSH_MS (6 s) flushing the persistent SSD cache. Its grace is now
SERVER_CLOSE_MS + FLUSH_MS + 2 s (13 s), the sidecar's close timeout is
SERVER_CLOSE_MS, and the whole-app quit deadline encloses the later of the
two children (15 s).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…D tier

The cold state label stores each block's image keys (label_format 2,
checksum domain v2); older files are rejected as corrupt and pruned.
lineage_keys, adopt_all and the state reads rebuild keys with the image
keys, and Lineage carries them wherever an image turn reaches, publishes
or restores a state. A restore with the same placeholder ids but a
different image never crosses: its keys differ, so it starts cold.

Dense and MoE VLM prefills now run on the lane state plan (book_chunk,
capture, reach) with and without a draft, and the VLM prepare arms the
SSD state restore. MoE manual paged turns end their turn states.

The MTP lane-state test also compares generated token id streams.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… states

Splash plans and publishes every request's state boundaries on a draft
load (configureDraftStatePlan, publishReachedStateBoundaries), each state
with its draft window. A scheduled autoregressive turn on a DFlash2 load
(the scheduler never speculates there) primed and prefilled plain and
published nothing.

- dense and MoE: the scheduled prime on a draft load
  (`prime_scheduled_draft_lane`) resumes only at a stored state below the
  last token (Splash acquireDeepest), else cold with its KV hit as the
  junction; the sequence's lane takes the state's window
  (QwenStateStorage::restore) and keeps it in `seq_windows`
- each prefill slice (`scheduled_draft_prefill`) runs the tapped forward
  with a ring-less DraftTapSink that continues the sequence's window, so
  two overlapped sequences each publish the states a whole turn of their
  prompt does; the turn's end gives the window to the idle lane, and the
  memory accounts carry the sequences' windows
- a disk restore promotes with the scheduled sequence's window
- a lane whose window did not come back keeps only the points a whole
  window past its resume (`keep_drawable_points`), also on image turns

Tests: interleaved scheduled sequences publish the whole turn's states
(dense, MoE); a scheduled request after a restart resumes from the disk
state with its window and continues it (dense, MoE).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The host's closeCaches dropped what each model's closeCache returned. It
now logs one line with how many caches flushed, missed the flush deadline
or failed, e.g. `[mlx] SSD cache close: 1 of 2 flushed, 1 not flushed in
time`. Every host user (mlx serve, launch claude, the desktop sidecar)
gets it; nothing is logged when no loaded model has an SSD cache.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… default

The SSD cache keeps one user-facing name for every family:
`persistPagedCache`, `--no-persist-cache` (and `--persist-cache` on
serve), `MLX_PERSIST_PAGED_CACHE`. Precedence flag > env > the entry's
default, and the default is on for `mlx serve`, `mlx agent`,
`mlx launch claude` and the desktop engine.

- server: `host/persist-cache` resolves the switch; the host writes the
  resolved value to MLX_PERSIST_PAGED_CACHE before any load, so the
  cold tier of qwen3, gemma4, muse_glimmer, lfm2 and lfm2_moe and the
  qwen3_5 / qwen3_5_moe state tier read the same answer; `host` reports
  it and serve prints it
- qwen3_5 / qwen3_5_moe: `Qwen35LoadOptions.persistPagedCache` > the env
  > off picks the state tier's mode (off = temporary, removed at close);
  `--max-cache-disk 0` turns the tier off instead of failing the load
- `persistentCache` / `--persistent-cache` are gone; `--max-cache-disk`
  and `--cache-dir` keep their names, and `--cache-dir` needs the switch on
- lm: the PagedConfigOverrideManager persist directive and its tests are
  back as on main
- agent: `--no-persist-cache` is lifted again and the spawned serve gets
  an explicit `--persist-cache` / `--no-persist-cache`

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…urn at a stateless KV hit

Two paths of the Splash state tier had no test through the code the serve
path runs.

- dense and MoE: two chatSessionStart requests on a DFlash2 load, driven
  through HybridSchedulerState::drive (continuous batching on), run as two
  live sequences; each publishes the states, GDN cells and draft windows a
  whole turn of its own rendered prompt publishes, and the windows go back
  to the idle lane. After a restart a session extending the first prompt
  resumes at its replay point (144) from disk, and the states past it
  (windows reaching below 144) equal a whole turn's of the longer prompt.
- an image turn on a draft load that resumes at a KV hit (128) on the
  session's live GDN cell, with no stored state there, publishes only the
  replay point (208) with the whole 40-row window a cold turn publishes;
  the checkpoint at 160, whose window would start at 128, is not published
  (keep_drawable_points in image_lane_prefill).

HybridSchedulerState gains a test-only enable_continuous_batching.
Mutations DS1, DS1m (the scheduled prime on a draft load primes plain)
and KI1 (image_lane_prefill keeps every point) turn them red. No defect
was found.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…xture names drop the stage label

The CI qwen3_5-dense runner has no vision headroom for any image turn, so
the image case reads MLX_TEST_VLM_MODEL_PATH like the other Qwen3.5 image
test. Drops checks for flags that never shipped and two stale sidecar lines
in the docs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Brooooooklyn
Brooooooklyn force-pushed the feat/kv-int8-s13-disk-state-tier branch from 5b8ce86 to 528dd9e Compare November 13, 2026 11:50
Brooooooklyn and others added 2 commits November 13, 2026 20:13
The qwen3_5 per-turn GDN sidecar group is gone, so its
<64-hex>.gdn_state.safetensors files were no longer indexed: they sat on
disk outside the quota and eviction forever. The index rebuild now unlinks
exactly that name shape, next to the writer-temp cleanup; foreign files
survive.

The dashboard's cold-object filename check is a hand parser now and
matches the groups that exist: conv_state, sliding_window and
dflash2_state. SIDECAR_GROUPS lists dflash2_state too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
After a restart a disk state was armed from its header alone: its KV
chain came back, and only then the GDN prime read the payload. A read
that failed discarded the state but kept the KV, and the dense and MoE
primes replayed GDN alone over it, so the turn decoded on a state the
KV never had.

As Splash pollRestores does, the prime now reads and checks a disk
state before it arms the chain: one that does not read back is
discarded and the next deepest taken, and the read waits for the GDN
prime, which takes it instead of reading again. If the KV still comes
back with a state chain but no exact GDN state at its end, the turn
restarts cold (no lookup) instead of taking a replay arm, for whole
turns, scheduled lanes and planned-MTP cores. Turns with no state
restore keep their paths.

Co-Authored-By: Claude Opus 5.5 <[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: 8f276fb6ae

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Brooooooklyn and others added 3 commits November 13, 2026 21:06
…it as the other qwen3 load tests

A cold 0.6B load on the hosted runner takes about 10 s, the default hook limit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…a scheduled lane and in the MTP cores

The lost-read tests reached only the replay-from-nothing arm: a turn that
keeps a RAM state below the armed disk state takes the checkpoint-replay
arm instead, and no test ran it, a scheduled lane's cold restart, or a
planned-MTP core's. Dense and MoE turns now resume above a RAM state
whose read is lost and must restart cold; a scheduled lane must book
nothing past its empty hit and end on a cold lane's logits; sync and
streamed MTP turns must decode what a cold MTP turn does.

A persistent test tier reopened while the last writer thread still held
the namespace's lock fell back to a temporary tier (about 1 run in 16);
the open now waits for the lock as a later process does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… their states

A text turn that extends an image session (a live continuation that keeps
the image positions) planned no state point: the lane cleared its points
whenever image positions were set. The points now go only when the GDN
state is dirty. Every lane-turn open (the plain and MTP opens on a load
without a draft, the DFlash2 turn plan and the scheduled draft lane) takes
the lane's per-block image keys, so a published state hashes its block the
way the turn registered it and its label carries the image keys. A later
image turn over the same image restores it, in process and from disk after
a restart; a text-only prompt with the same ids never does.

Tests (dense and MoE): an image turn, a text continuation that publishes its
replay point at 176 under the image keys, an image turn that resumes there on
a cold image turn's logits, then a restart where a text-only prompt restores
nothing and the image turn resumes at 176 from disk with the stored cell.
Mutations IC1 (clear the points while image positions are set) and IC2 (open
the lane turn with no image keys) turn both red.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Brooooooklyn
Brooooooklyn merged commit 949cdf0 into main Nov 13, 2026
14 checks passed
@Brooooooklyn
Brooooooklyn deleted the feat/kv-int8-s13-disk-state-tier branch November 13, 2026 14:37
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

model-e2e Run the heavy Model E2E workflow (per-family real-checkpoint tests) on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant