Skip to content

feat(kv-int8): one memory ledger governs every claim - #374

Merged
Brooooooklyn merged 6 commits into
mainfrom
feat/kv-int8-s11-memory-ledger
Nov 12, 2026
Merged

Brooooooklyn merged 6 commits into
mainfrom
feat/kv-int8-s11-memory-ledger

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Nov 12, 2026 •

Copy link
Copy Markdown
Contributor

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

@Brooooooklyn
Brooooooklyn added this pull request to stack #344 November 12, 2026 05:07
@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: 06d0d75b-f557-4baf-9926-27b1aa32d5fe

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-12T16:02:40.116961Z dd91726 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: 69c4040455

ℹ️ 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: 177aff578e

ℹ️ 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: 08048a1729

ℹ️ About Codex in GitHub

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

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

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

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

@Brooooooklyn
Brooooooklyn force-pushed the feat/kv-int8-s11-memory-ledger branch from d81f71b to 8478008 Compare November 12, 2026 13:41
@Brooooooklyn
Brooooooklyn force-pushed the feat/kv-int8-s37-desktop-restart-policy branch from 9c3213d to 84e7bb6 Compare November 12, 2026 13:41
@Brooooooklyn
Brooooooklyn removed this pull request from stack #344 November 12, 2026 15:43
@Brooooooklyn
Brooooooklyn force-pushed the feat/kv-int8-s37-desktop-restart-policy branch from 84e7bb6 to 42feea2 Compare November 12, 2026 15:57
Base automatically changed from feat/kv-int8-s37-desktop-restart-policy to main November 12, 2026 15:57
Brooooooklyn and others added 6 commits November 12, 2026 23:57
Qwen3.5 dense and MoE memory goes through one process ledger (Splash
MemoryLedger / MemoryGovernor). Every allocation point takes a claim:
scheduled rows before each step, whole turns at each paged step, GDN
cells, draft state, publications and vision. A refused claim frees
units in Splash order, then waits, yields its lane or fails.

- Host rule and a 500 ms control pass; margin max(1 GiB, 2%) for the
  qwen3_5 plan, other families keep 15% + 1 GiB.
- Scheduled lanes: per-row claims, Splash judge and yield order,
  Start / InService admission, resume to the suspended KV target.
- Serial lane: a host-refused AR or DFlash2 decode step suspends and
  replays its tail (greedy exact).
- Waits end in resource_timeout after 30 s; capacity_exhausted and
  metal_out_of_memory map to 503 in the server.
- GPU OOM fails the model's running rows and resets its caches.
- Status: memoryGovernorStatus() and /health memory_governor (accounts,
  claims, TTFT parts, decode-gap causes, counters).
- Stops: a stopped running row ends in its step, never refused; a
  stop in a serial lane's wait completes on what the turn generated;
  a suspended request's end wakes the waits.
- A DFlash2 lane replayed after a suspend drops its pending GDN rows.
- Deleted: engine::reclaim, the in-order L1-L3 reclaim paths,
  DraftRefusal, MLX_SCHED_RESERVE_FULL_ISL.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A decode turn's num_tokens already counts its pending token, so the
decode work end is num_tokens + the draft allowance (Splash
Engine::workEndOf). The extra token claimed a block the step never
writes at a block boundary, refusing or suspending the lane.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- 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 once).
- The host pass's settle deadline is per model: an empty model's pass
  no longer spends another model's reclaim.
- A DFlash2 verify lends its lane (GDN cells, pending rows, draft
  window) to the target across its claim, so a suspend's vacate drops
  it before the wait (Splash QwenStateStorage::releaseLane), dense and
  MoE.
- A take that removed its unit is Met though it measured nothing
  (Splash Cache::take), so the ledger lists the units again.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- A decode row whose pending token ends its turn (EOS, max_new_tokens,
  repetition) claims nothing, as Splash Engine::commit ends the lane there.
- An MTP lane's admission reserves its draft state's fixed part, and every
  row, prefill slices included, claims its draft K/V growth.
- MTP's AR step runs under paged_step_claimed (dense and MoE): a refused
  growth waits instead of failing context_length_exceeded.
- A qwen3_5 whole turn's GPU OOM is classified at its boundary
  (run_paged_turn, run_multimodal_turn), as Splash
  NativeRuntime::executionFailed: metal_out_of_memory and the model reset.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A bytes need takes the pool's dead leaves and cuts the extent they empty
(Splash Cache::takeReclaim), keeping the claim's and queued chains. A stop
during a suspended lane's replay completes the turn on its tokens. One
row's GPU OOM fails every turn its step completed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A scheduled lane's prefix preparation (GDN replay of a cached prefix) at
admission or at a suspended lane's resume that MLX fails for Metal memory
now fails the request metal_out_of_memory and resets the model before the
next step, like Splash NativeRuntime::executionFailed around Engine::tick.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Brooooooklyn
Brooooooklyn force-pushed the feat/kv-int8-s11-memory-ledger branch from 8478008 to dd91726 Compare November 12, 2026 15:58
@Brooooooklyn
Brooooooklyn merged commit 58dc868 into main Nov 12, 2026
1 check failed
@Brooooooklyn
Brooooooklyn deleted the feat/kv-int8-s11-memory-ledger branch November 12, 2026 15:58
Brooooooklyn added a commit that referenced this pull request Nov 12, 2026
…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]>

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

ℹ️ 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 on lines +2574 to +2578
self.grow_shortfall(&self.allocator_guard(), restorable.saturating_add(held));
if shortfall > 0 {
self.try_grow_pool(shortfall);
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Size restore growth from the actual cold-cache hit

With SSD caching enabled, a long prompt now grows the pool for every block absent from the hot cache before checking whether any corresponding SSD blocks exist. On an empty cold cache, this allocates the entire prompt's KV capacity even though the restore returns a miss and prefill only needs its next chunk. This defeats on-demand pool growth, introduces a large allocation and synchronization before prefill, and consumes memory that concurrent lanes could otherwise use. Probe the restorable cold chain first and grow only for the blocks that will actually be restored.

Useful? React with 👍 / 👎.

),
)
})?;
let built = build()?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Record driver refusals from initial pool construction

If Metal rejects a buffer allocation during initial pool construction, build()? returns without setting START_REFUSAL, so start_under_growth_lock immediately propagates the error instead of applying its driver-refusal retry window. The other paths that set START_REFUSAL only perform registration and logical reservation checks, so they cannot classify this actual driver rejection. Classify allocation failures from the build as DriverRejected at the runway stage while leaving non-allocation construction errors non-retryable.

Useful? React with 👍 / 👎.

Brooooooklyn added a commit that referenced this pull request Nov 13, 2026
…old tier

The #374 governor refuses Optional claims on a host short of spare memory
(the 7 GB hosted runner). A refused dense GDN ladder rung was dropped, so
nothing reached the cold tier and the restart restored nothing. Splash
falls back to publishStateToDisk; the rung now stays for this turn's
sidecar capture and is dropped at the turn's end.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brooooooklyn added a commit that referenced this pull request Nov 13, 2026
…he cold tier

MoE dropped a ladder rung the #374 governor refused, so on a host short
of spare memory no MoE recurrent state reached the cold tier. Mirrors
the dense fix (Splash publishStateToDisk): the deepest refused rung is
held for this turn's sidecar capture and dropped at every turn end.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brooooooklyn added a commit that referenced this pull request Nov 13, 2026
…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]>
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.

1 participant