Skip to content

feat(scheduler): requeue requests under memory pressure and cache cancelled prompts - #4509

Merged
jundot merged 6 commits into
mainfrom
feat/memory-pressure-requeue
Oct 14, 2026
Merged

jundot merged 6 commits into
mainfrom
feat/memory-pressure-requeue

Conversation

@jundot

@jundot jundot commented Oct 13, 2026 •

Copy link
Copy Markdown
Owner

This replaces the pause-and-resume stack in #4478, #4479, #4480, #4481, #4482, #4483, #4484, #4485, #4486, #4487, #4488 and #4489 with a smaller change aimed at the same root cause. It was developed from @e-Evolution's idea and analysis in #4440. The never-fits capacity API and the cached-media suffix route from that stack are not part of this PR. The external prefill gap in the cancel path was reported by @xain, and the TurboQuant gap by @e-Evolution.

Summary

Two changes so the server stops throwing away work it has already done.

  • Memory pressure no longer fails every request. When memory gets tight, running requests are paused instead of aborted. Their progress is saved to the SSD cache, and they continue from where they stopped on the same stream, one at a time. A request that can't be paused (for example, the only one running, or one with the SSD cache off) is aborted as before.
  • Cancelled prompts stay cached. If a client disconnects or cancels a request, the prompt work done so far is saved. Sending the same prompt again starts from there instead of from scratch.

Works with text and vision models. No new settings.

Details

  • Requests are kept only at the hard watermark outside the emergency tier. The emergency path is unchanged.
  • Not kept, aborted as before: a lone request, no paged SSD cache, DFlash, SpecPrefill, VLM MTP, or a request already requeued twice.
  • The resumed prompt re-prefills at most one cache block of the generated tail.
  • With TurboQuant KV on, a partial prefill is converted to the TurboQuant layout before it is stored, the same conversion a finished prefill gets.

Validation

Qwen3.8-27B-oQ4e-mtp on the VLM engine with Lightning MTP, M3 Ultra.

Three concurrent long prompts (38k, 32.5k and 28k tokens) with a 40 GB custom ceiling and a 0.8 hard threshold:

main this PR
Completed 0 / 3 3 / 3
Requests aborted at the hard watermark 3 0

The requeue stored the live rows in 0.8 to 1.0 s, and the resumed text continues at the seam with no repeated or missing tokens.

Cancel, then resend the same request:

main this PR
Cancel 60 s into a 38k-token prefill cached 0, TTFT 102.8 s cached 28,672, TTFT 34.1 s
Cancel during decode (32.5k-token prompt) cached 0, TTFT 80.7 s cached 32,549, TTFT 0.5 s

Notes

  • Requeued requests resume one at a time until all of them finish, so a later request's stream pauses while the earlier ones run. In the pressure run above, the pause was 40 to 60 s.
  • On hybrid models the resumed tail can be up to one 4096-token cache block.

…orting them

At the hard watermark the enforcer asks the scheduler to keep a busy model's requests. The scheduler stores their KV to the paged SSD cache, drops the batch in one step, and resumes them one at a time on the same stream.
…uest

A client disconnect or cancel now stores a decoding request's prompt and a chunked prefill's progress, so a resend of the same prompt restores them.
@xain

xain commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

A gap in the cancel path: external (non-chunked) prefill

Thanks for the smaller rewrite — this is much easier to reason about than the stack. My independent numbers line up with yours: cancel during decode on a 32.5k-token prompt gives cached 32,549 / TTFT 0.5 s on your side and cached 28,196 of 28,198 / 0.53 s on mine.

I think the cancel-keeps-cache path misses one case, and it happens to be the one long-prompt agent traffic hits.

What I read in _do_abort_request

After keep_cache = keep_cache and self._abort_keeps_cache(request), the store is reached from two places:

  • request_id in self.running and a live uid → _cleanup_finished({request_id})
  • request_id in self._prefill_states → _submit_abort_prefill_store(request, state)

With chunked_prefill: False (the default — settings.py, and what I run), a cancel during prefill never reaches either. External prefill raises _PrefillAbortedError from _do_external_prefill, and the caller routes it to _cleanup_prefill_abort_request → _do_abort_request. At that moment the request is in neither set: it has not been inserted into the batch yet (so it is not in self.running), and _prefill_states only exists for the chunked path. So both branches fall through and the plain teardown runs — nothing is stored.

This PR does not touch _cleanup_prefill_abort_request or _do_external_prefill (_do_external_prefill appears only in a comment), so I don't think that path is covered.

Evidence from my deployment

  • Both hosts: scheduler.chunked_prefill = False.
  • Server logs: 11 lines of Prefill interrupted at N/M tokens — that message is emitted inside _do_external_prefill, so those are external-prefill cancels — and 0 lines matching chunked prefill / _advance_chunked.

That is exactly the shape of the problem this PR targets: an agent client gives up on a long cold prefill, and the resend starts from zero.

The missing branch, if it helps

I had implemented this case before finding the stack, and it is small. The live prompt_cache is only reachable at the abort raise inside _do_external_prefill, so it stages there:

  • before raise _PrefillAbortedError(...): K = (base_size + processed_tokens) rounded down to a block boundary; _extract_cache_states(prompt_cache) + mx.eval on the engine thread; stash on the request
  • in _do_abort_request: submit that staged payload through _get_boundary_store_override + _merge_boundary_with_full_cache, then defer the snapshot rmtree and the cache-reference drop until the future lands (the store runs off-thread, same as your _submit_abort_prefill_store)

Measured on DeepSeek-V4.1-Flash-oQ4e-mtp (40 layers, all DeepseekV41Cache(ArraysCache), block_size 2048, TurboQuant off), Mac Studio M3 Ultra 512GB:

scenario cached on resend
cancel ~31 s into a 142,852-token prefill 18,432
cancel ~45 s in, during decode (28,198-token prompt) 28,196 of 28,198

For the decode row: 5 runs per arm, alternating, no overlap between arms (feature off → 0 cached and a full re-prefill every time). The prefill row is a single run, so treat it as an existence check.

And repeated time-limited attempts converge: one 238,484-token prompt cut at 42 s each time gave reused_kv_tokens 0 → 26,624 → 49,152 → 71,680.

Happy to send that as a patch or a PR against this one if it's useful — or leave it to you if you'd rather keep the shape of the change yours. I can also just test a branch on this model and report, whichever is more useful.

With chunked prefill off, a cancel lands inside the external prefill loop, where the request is neither running nor a chunked prefill. Extract the progress at the abort point and store it the same way as a cancelled chunked prefill.
@jundot

jundot commented Oct 14, 2026

Copy link
Copy Markdown
Owner Author

@xain Confirmed. With chunked prefill off (the default), a cancel happens inside the external prefill, so the progress wasn't saved. My own test had chunked prefill on, so I missed it.

Fixed in aa5d2f6. On Qwen3.8-27B with chunked prefill off, cancelling 60s into a 38k prompt and resending now reuses 24,576 cached tokens, and TTFT drops from 106s to 40s.

Thanks for catching this. If you get a chance to try it on DeepSeek-V4.1, that would help too.

@e-Evolution

Copy link
Copy Markdown
Contributor

With TurboQuant KV enabled, neither the requeue nor the cancel path keeps any tokens

I ran #4509 through our pause/resume harness, rebased cleanly on main 64bf5d1, next to main itself. Setup: M5 Max 128 GB, Qwen3.8-27B-oQ4e-mtp with TurboQuant KV 4-bit and MTP, memory ceiling pinned at 48 GB, three greedy prompts of 130k, 115k and 100k tokens sent together.

The requeue does what it promises. main aborts all three requests 26 s in; #4509 requeues them once and all three finish (3/3). Same result with images (3/3 vs 0/3).

But nothing reaches the SSD cache. Pressure hit while the three were still prefilling, and the log shows:

Memory pressure: requeued 3 request(s) in 0.2s; tokens kept in the SSD cache: b12d7080 0/12288, 5f237002 0/4096, 5b68a2a3 0/4096

_store_for_memory_requeue returns 0 for a prefill row when _turboquant_kv_bits is set, so each request re-prefills from zero. Client cancel has the same gate: _prepare_abort_prefill_store returns None under TurboQuant. Cancelling a 110k prompt at 60% of its prefill and resending gave cached 0 and a full 110,031-token re-prefill, with chunked prefill both off and on. The new external path in aa5d2f6 goes through the same function, so I expect the same result there. I checked that in code but did not rerun it.

The comment says prefill KV is still dense while TurboQuant blocks use another layout, so this looks like a known limit rather than a slip. Two options, depending on what you prefer:

  1. Store the dense prefill KV as plain blocks, or convert it to the TurboQuant layout before writing.
  2. Log the skip explicitly (for example skipped: TurboQuant prefill) and note the limit in the PR or docs, so a 0/12288 is not read as a failure.

Two smaller observations, in case they are useful:

  • Lone request: with one 130k request, the prefill guard reserves its KV up front, so it fits at a 36 GB ceiling and is rejected at 35 GB or below. It never reached hard pressure, so the lone-request abort did not show up in practice.
  • DFlash: on the oQ8e DFlash model, admission rejected two of three requests after 60 s of sustained pressure (admission_paused), so the requeue never ran.

Decode rows with TurboQuant were not exercised, since pressure always hit during prefill. Happy to rerun anything on aa5d2f6 if that helps.

@xain

xain commented Oct 14, 2026

Copy link
Copy Markdown
Contributor

Tested on DeepSeek-V4.1 with chunked prefill off — the fix holds here too

Ran aa5d2f65d on the layout from my earlier comment (DeepSeek-V4.1-Flash-oQ4e-mtp, 40 layers of DeepseekV41Cache(ArraysCache), block_size 2048, TurboQuant off). The branch's engine pins matched my install exactly (mlx-lm / mlx-embeddings / mlx-vlm / mlx-audio), so the package dropped in without a rebuild.

scenario tokens done at cancel cached on resend
cancel during external prefill (chunked prefill off) 12,288 of 142,852 12,288 (100%)
cancel during decode (28,198-token prompt) prefill complete 28,196 of 28,198, TTFT 0.4 s

The log for the first row:

Prefill interrupted at 12288/142852 tokens: 1 request(s) aborted

and the resend reported cached_tokens 12,288 — everything that had been computed was reused, so there is no loss at the seam. Before the fix this scenario gave cached_tokens 0 and a full re-prefill on this model.

One caveat on scope: this was with TurboQuant KV off, so it does not speak to the TurboQuant gate e-Evolution raised.

@jundot
jundot marked this pull request as ready for review October 14, 2026 03:57
@jundot

jundot commented Oct 14, 2026

Copy link
Copy Markdown
Owner Author

@e-Evolution Confirmed. The prefill store skipped TurboQuant because the prefill KV is still dense at that point. Rather than logging the skip, the partial prefill cache now gets the same conversion a finished prefill gets before it is stored, so the blocks match what a normal TurboQuant request writes. This covers the requeue, the chunked cancel and the external cancel path.

Fixed in e0c956f. On Qwen3.8-27B with TurboQuant 4-bit, the requeue log now shows 8192/8192 for each prefilling row instead of 0. I also ran three turns of 25k, 53k and 80k tokens with two mid-prefill cancels per turn, so every resend restored a TurboQuant prefix that had been saved, restored and extended again. All needles were found in every turn, the answers stayed coherent, and they drifted from a cold no-cache run no more than a normal TurboQuant prefix hit does.

The lone-request and DFlash cases behave as intended, since neither is requeued. Thanks for running this through your harness.

@jundot
jundot merged commit 6d17522 into main Oct 14, 2026
1 check passed
@e-Evolution

Copy link
Copy Markdown
Contributor

Thanks for e0c956f. I checked it with tests that compare the stored blocks byte for byte against a TurboQuant conversion of the whole prefix: requeue of a prefilling row, chunked cancel and external cancel. All match. The in-place conversion is fine where you use it, since those caches are dropped right after the store.

For the record, I also ran aa5d2f6 against our stack on the same main (2c53654): same harness and runtime, Qwen3.8-27B-oQ4e-mtp with TurboQuant 4-bit and MTP. With three long requests decoding at a 48 GB ceiling, #4509 finishes 3/3. Our stack gets 2/3 because it cannot pause a batched Lightning MTP decode row. So your requeue covers a case ours did not.

Three things the stack does that #4509 does not, in case any are worth a small follow-up. Each lives in its own PR, so you can take them separately or ignore them:

  1. Never-fits requests (feat(memory): reject never-fits requests with the numbers and let fits-later requests wait #4485, fix(memory): raise the never-fits line by the hot cache and keep the stall clock across park holds #4489). A 60k-token prompt with a huge max_tokens at a 42 GB ceiling returns HTTP 200 and never finishes. The stack answers at admission with a 400 context_exceeds_capacity, carrying the required and capacity bytes and the max viable context. A client agent can then compact and retry.
  2. Admission under sustained pressure (feat(memory): reject never-fits requests with the numbers and let fits-later requests wait #4485, fix(scheduler): time the admission stall by progress and admit a lone head that fits #4488). This is separate from requeue. On the 8-bit DFlash model, three requests at 56 GB give 1/3 on feat(scheduler): requeue requests under memory pressure and cache cancelled prompts #4509, because the other two are rejected after about 60 s of admission_paused. With the fits-later wait and the lone-head admission, the same load completes 3/3, one after another.
  3. Partial requeue (feat(memory): abort one victim instead of all when nothing is parkable #4480). When one live row cannot be requeued, request_memory_requeue() returns 0 and every request is aborted. feat(memory): abort one victim instead of all when nothing is parkable #4480 aborts one victim at a time and re-measures. Here that could mean aborting only the blocked row and requeueing the rest.

If you are not interested, feel free to close the stack PRs whenever it suits you. They have done their job as a reference.

jwiegley added a commit to jwiegley/omlx that referenced this pull request Oct 20, 2026
On v0.7.0 a request with max_tokens of 0 or below failed every request
on its model: it was queued and fully prefilled, then mlx-lm's
BatchGenerator.insert raised "Sequence N's max_tokens must be > 0."
inside scheduler.step(), and engine_core's loop answers any step error
with scheduler.fail_all_requests(). v0.7.1's requeue work (jundot#4509) clamps
the insert cap to 1 (_insert_max_tokens), so such a request no longer
takes the engine down, but it is still accepted: the whole prompt is
prefilled and the client gets one token and HTTP 200, where the OpenAI
and Anthropic APIs answer 400. And insert still refuses a row for other
reasons (an empty prompt), which still fails every request on the
engine.

Fix it in three places:

- The four generation routes check their cap first, before model load,
  lease or queueing: max_tokens on /v1/chat/completions (which also
  receives max_completion_tokens through the validation alias),
  /v1/completions and /v1/messages, and max_output_tokens on
  /v1/responses. A value below 1 raises InvalidRequestError, so the
  client gets the server's existing 400 validation shape:
  invalid_request_error with the field as param. The check runs before
  a StreamingResponse exists, so streamed requests get the 400 too.
- Scheduler.add_request refuses max_tokens below 1 before it tracks or
  queues the request. That covers callers that do not come through
  these routes, such as a model-settings default. engine_core's
  add_request already cleans up and re-raises the typed error to its
  caller alone.
- Both BatchGenerator.insert call sites catch ValueError and fail only
  the request being inserted: the direct insert in _schedule_waiting
  (cache hits, one-shot prefills and SpecPrefill) and
  _insert_prefilled_request, which completes a chunked prefill. On
  v0.7.1 the latter runs through
  _complete_chunked_prefill for both the head request and a packed
  companion, and inline for a first chunk that completes its prefill;
  each caller reports the refusal. mlx-lm validates every row (a non-empty
  prompt, max_tokens > 0, one option per segment) before it touches
  batch state, and each call inserts a single request. The refused
  request is torn down through _do_abort_request, the same path a
  client abort between prefill and insert takes, and gets a
  finish_reason="error" output. Other ValueErrors from insert are
  therefore isolated too, while step errors outside insert keep the
  fail-all recovery, because there the batch state is unknown.

Tests:
- Every route rejects 0 and -5, streamed or not, with 400,
  invalid_request_error, the field as param and the message, and
  never asks the pool for an engine. max_completion_tokens is covered
  too, and a cap of 1 is accepted on every route.
- The installed mlx-lm's insert raises for max_tokens 0 or -5 and for
  an empty prompt without advancing uids or queueing anything; the
  isolation depends on this.
- Scheduler.add_request refuses 0 and -5, accepts 1, and leaves
  nothing tracked or queued.
- A refused insert (an empty prompt, the refusal that still reaches
  insert past the clamp) fails only that request on the cache-hit path,
  the chunked-prefill path, a first chunk that completes its prefill and
  a packed companion. The next queued request is inserted, a request
  already decoding stays running, another request still mid-prefill
  keeps its prefill state and tracking, the refused request's
  paged-cache blocks are released for eviction as a client abort does,
  and after a lone refusal the scheduler goes idle and a late abort of
  the refused id is a no-op.
- With mlx-lm's real BatchGenerator and a tiny llama, an empty prompt
  fails alone while a decoding request finishes all its tokens.
- scheduler.step() returns the refusal as that request's error output
  instead of raising.
- EngineCore.add_request raises InvalidRequestError to its caller
  alone, leaves no collector behind, keeps an admitted request, and
  never calls fail_all_requests.

Without the fix, the route, admission and isolation tests fail.

Rebased onto v0.7.1 (was 9744036 on v0.7.0, with 0238c8a's tests
folded in). The insert tests now trigger the refusal with an empty
prompt, because the clamp turns their old max_tokens of 0 into 1; the
chunked-prefill plumbing follows upstream's _complete_chunked_prefill;
the first-chunk, packed-companion and real-BatchGenerator tests are new.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UnUQdL7be1M9NXFzY6AHab
Claude-Session: https://claude.ai/code/session_01G7DbsyUGKr5LUjAL6Vr533
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