Skip to content

fix(memory): raise the never-fits line by the hot cache and keep the stall clock across park holds - #4489

Closed
e-Evolution wants to merge 46 commits into
jundot:mainfrom
e-Evolution:stack/s9-scheduling-followups
Closed

e-Evolution wants to merge 46 commits into
jundot:mainfrom
e-Evolution:stack/s9-scheduling-followups

Conversation

@e-Evolution

@e-Evolution e-Evolution commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Slice 12 of 12 of the pause-and-resume cycle proposed in #4440 (the improvement is explained in the write-up's section The strategy: pause, don't abort). Depends on #4488 (S8). GitHub shows every earlier unmerged slice in this diff; please review only this slice's 4 commits below. I keep it as a draft and rebase it on main after the previous slice merges.

  • The never-fits gate counts the releasable hot cache: it raises the line by what the hot cache can release instead of crediting the request, matching fix(memory-guard): free hot cache instead of rejecting prompts #4252's admission credit.
  • With park on, the progress clock also runs while a park hold is active (a parked or decode-paused request running solo or waiting), so the head queued behind it is not failed while that request progresses; the fixed clock restarts when the hold ends. With park off, main's clock is unchanged.

Default: Memory scheduling (hot cache line) or park (stall clock across holds); both off by default.

Stack and merge order

Each slice applies on the one before and keeps main's behaviour with its switches at their defaults. Merge in this order:

# PR Slice
1 #4478 P-a: Prefill progress commit
2 #4479 P-b: Prefill park instead of abort
3 #4480 S1: Single victim and exact-chain cache primitives
4 #4481 S2: Decode pause and resume
5 #4482 S3: Memory-aware resume priority
6 #4483 S5: Cached-media text suffix through the chunked path
7 #4484 G: memory_scheduling setting
8 #4485 S4: Never-fits gate, fits-later wait, capacity API
9 #4486 S6: Resume under the hard watermark
10 #4487 S7: Enforcer: external-loop prefills, no live victim, emergency pause-first
11 #4488 S8: Admission progress clock and solo admission
12 this PR S9: Hot cache in the never-fits line, stall clock across park holds (this PR)

Commits in this slice (6 files changed, 458 insertions(+), 31 deletions(-)):

2b83b558 fix(scheduler): keep the progress clock while a park hold is active
5de0dcbd fix(memory): count the releasable hot cache in the never-fits gate
f0dfe4e8 fix(memory): raise the never-fits line by the hot cache instead of crediting the request
9ff04734 fix(scheduler): restart the fixed stall clock when a park hold ends

Validation

  • Focused: python -m pytest tests/test_memory_scheduling_gate.py tests/test_scheduler_capacity_gate.py tests/test_scheduler_admission_progress.py tests/test_scheduler_prefill_memory_guard.py tests/test_process_memory_enforcer.py tests/test_prefix_cache.py tests/test_paged_ssd_cache.py tests/test_engine_core.py
  • CI's command (pytest tests/ -m "not slow and not integration" -n 3 --dist loadgroup, Python 3.11, a venv with main's pins) at this slice's tip on main f3ad34d: 17,580 passed, 3 failed, 721 skipped; main f3ad34d: 17,119 passed, 3 failed, 718 skipped. The 3 failures are tests/test_gemma4_rendering.py on both (a local asset model without a chat template).
  • Ruff: no new finding against main; Black is clean on the changed lines. Every commit imports omlx.server and omlx.scheduler and collects its tests.

The real-model numbers below are in the write-up's Final results section.

Real-model runs: Apple M5 Max (128 GB), macOS 27.0.1, Python 3.11, Qwen3.8-27B-oQ4e-mtp (4-bit, Lightning MTP, TurboQuant 4-bit KV), one server at a time, one run per scenario. They used my fork rebased on main c0b1056 (this whole cycle plus my fork's other features), against main c0b1056 from the same venv; the stack on current main was not run on the real model.

  • A real-rig case runs park on and memory scheduling off: a request paused twice while alone resumes as the solo request, and the head queued behind it waits and then completes (the fixed clock failed it after 60 s in a forced-pressure run).

What remains untested: Not isolated on the real model. One Mac and one model family.

Checklist

  • I read CONTRIBUTING.md.
  • I understand every change in this PR and can explain it in review.
  • For UI or UX changes, I attached before and after screenshots.

Contribution from the lead maintainer of ADempiere (https://github.com/adempiere/adempiere/tree/hotfix/3.9.4.002). Author: victor.perez@e-evolution.com.

…during prefill

Blocks were stored only when a request finished, so a request aborted
mid-prefill lost all of its prefill work and a re-issue of the same prompt
prefilled from token zero.

With prefill_progress_commit_blocks = N (0 = off, the default), chunked and
external prefill now store every N completed blocks under the request's own
block table, which stays alive so later commits and the final store extend
it. Each commit window is detached from the live cache; TurboQuant layers are
converted with the same rules as the final conversion (the codec is
per-vector and fixed-seed, so windowed blocks are byte-identical to
whole-prefix ones), and a restored TurboQuant prefix is sliced from its packed
state. Commits are skipped under soft or hard memory pressure, while a
previous commit is in flight, and for prompts that are not a plain token
prefix. Aborts and prefill failures wait for an in-flight commit and leave the
committed blocks in the prefix cache.

A request requeued after a prefill memory failure still prefills cold, as
_requeue_or_fail_prefill documents, when the setting is on.

BlockAwarePrefixCache.store_cache gains cache_covers_suffix_only so a window
longer than the stored prefix is not mistaken for a full-sequence cache.
Add scheduler.prefill_progress_commit_blocks to the scheduler settings (and
OMLX_PREFILL_PROGRESS_COMMIT_BLOCKS), validate that it is not negative, and
pass it to SchedulerConfig.
… MLX thread

Teardown of a request with an in-flight incremental prefill commit no longer
waits up to 60s on the inference thread. The destructive steps (block release,
snapshot retirement and cleanup) are queued and run on the scheduler thread
once the commit future has finished, whether it succeeded or not. Commits get
their own single-thread executor so they never queue behind final stores, and
the final store of a request is chained after its own commit on the store
worker. Shutdown waits a bounded time and abandons stuck commits.
…commit

A stuck commit blocked the final-store worker forever, holding store-gate
slots and stalling admission. The wait is now bounded; on timeout the
final store is skipped, logged once, the gate slot is released and the
table and snapshot teardown stays deferred behind the commit.
…dule

Scheduler.shutdown was no longer the first shutdown definition in
scheduler.py, so the registry-cleanup guard test inspected the
executor's shutdown instead and failed (a regression from the deferred
commit teardown earlier in this series). Behavior is unchanged:
Scheduler.shutdown still releases registry rows by model.
Add scheduler.memory_pressure_park, max_parks_per_request and
park_resume_ok_polls settings (env overrides, default off). At hard,
non-emergency pressure the enforcer asks each scheduler to park a prefill
victim and defers the abort while one is parkable; the legacy abort runs
when nothing is left to park, the deferral budget is spent, or pressure
is an emergency. Every poll reports its level to the schedulers for the
resume hysteresis.
… of aborting it

With memory_pressure_park on, the scheduler consumes the enforcer's park
flag at step start and parks one victim per step: the most recent
chunked-prefill arrival, never the oldest while another is parkable. The
request keeps its stream, prompt and arrival time, drops its live cache
through the deferred teardown, and re-queues in arrival order ahead of
newer requests. It resumes after park_resume_ok_polls consecutive ok
polls with a fresh prefix lookup that restores the committed blocks,
bypasses the cold-retry guard and the admission-stall timeout, and its
committed blocks are pinned (block refs plus SSD index hashes) until the
resume, finish or abort. Bulk pressure aborts spare parked requests.
…el loaded

abort_all_requests spared parked requests whenever no reason was given, so
idle-LRU eviction and the emergency busy-victim path left them orphaned or
blocked the pending unload from draining. Make it an explicit spare_parked
keyword (default False) and pass True only from the non-emergency hard
keep-loaded path.
… blocks reclaimable from RAM

- clear parked on abort and guard the deferred pin by request identity
- consume the ok streak on resume; max-hold and stale-monitor escapes resume one per pass
- stop pinning parked blocks in the hot cache; SSD pin plus dirty-eviction write-back keeps them restorable
- count the settle window in enforcer polls instead of queries
- replace the victim sentinel with an explicit flag
…ry skip reason

Conversations that carry an image resend it every turn, so the VLM engine
prefills them through the external loop with fused embeddings and
request-wide media cache keys. That loop never called the incremental commit
and the commit guard excluded any prompt with media keys, so long prompts
never became durable and were re-prefilled in full after an abort.

Media prompts now commit under the same extra-key arguments their final
store uses (block keys depend only on where a block ends), except for models
that need an atomic multimodal prefix. Every early return of the commit path
logs its reason once per request at INFO, each commit logs its token range,
and a park request that finds no victim logs why per request.
…rdown watchdog

The engine-close watchdog exits the process after 60s without SSD write
progress. A final store waited up to 120s for a stuck commit and shutdown
could spend 40s on commit waits before reporting any progress.

The final-store wait now polls and stops as soon as shutdown cancels the
commits, the shutdown waits total at most 20s, and a commit that is still
writing is reported to the watchdog as persistence progress.
On the non-emergency hard path with no parkable request, abort only the
live request holding the most KV (newest arrival breaks ties) and keep
the rest running; the enforcer re-measures next poll, at most one victim
per poll. Emergency and unload keep abort-all as a safety brake. Parked
requests stay spared. Gated by the memory.abort_single_victim setting
(off by default).
store/fetch/restore_exact_prefix take an optional domain_key that enters
every block hash of the chain, so two requests with identical tokens (or
identical image placeholders over different images) never collide, and
domain blocks stay out of dedup and ordinary prefix matching.

Scheduler._pin_blocks generalizes the parked-prefill pin; _pin_exact_chain
holds a stored exact chain all-or-nothing in the block pool and the SSD
index until _unpin_parked releases it.
The single-victim abort is deferred to the next scheduler step, so a
following enforcer poll could see the first victim's memory still held
and sacrifice a second request, cascading back toward abort-all. The
enforcer now tracks the draining victim: while its abort is pending
(EngineCore.memory_victim_pending) or until one more poll after it ran,
no other victim is chosen, bounded by _SINGLE_VICTIM_SETTLE_MAX_POLLS.
Relief below hard forgets it; emergency still aborts everything.

A failing engine hook now falls back to abort-all for that poll, and
abort_one_request_for_memory reports a chosen-but-not-aborted victim with
skipped="no_client" or "already_finished" instead of the None that means
no victim at all. The single-victim block no longer splits the
emergency/spare_parked comment from its call.
Scheduler.request_decode_pause asks for a decoding row to be paused at
the next step start. The pause emits the row's pending token through the
normal response path (a token that finishes the request is left to the
step, which completes it normally), stores the row's KV as an exact chain
under a request domain, pins it, and removes the row the way an abort
does while the request keeps its output, detokenizer, parser session,
rope deltas and client stream. A _DecodeResume record keeps the sampler,
logits processors, stop machine, remaining max_tokens and the KV token
sequence; the request waits parked in arrival order.

_park_exclusion_reason names the v1 exclusions for decoding rows:
SpecPrefill, VLM-MTP, DFlash, active MTP speculation, no paged SSD tier,
a split-GDN layout without an exact sidecar writer, and layouts that
cannot round-trip. Nothing selects decoding victims yet. Until the exact
resume lands, re-admitting a paused row ends it with the structured error
decode_resume_lost (with its token counts) instead of waiting forever.
A re-admitted paused row skips the prefix lookup, prefill and preflight:
restore_exact_prefix rebuilds the row's KV under its request domain, the
pins are released, and the row is inserted with the last output token as
kickoff, the saved token sequence as all_tokens, the remaining max_tokens
and the stashed sampler, logits processors and stop machine. The RNG is
not reseeded and prompt usage is not counted again; the batched-decode
gate already counts prompt plus output.

An exact-restore miss (or a restored length that disagrees) ends the
request with the structured error decode_resume_lost, counted in the park
stats. Greedy output after a pause at decode token 1, 255 or 256 equals
an uninterrupted run, alone or beside a second row, inline and split GDN.
…code pause

A resumed decode row got a fresh stop-sequence matcher, so a multi-token
stop sequence that began before the pause was missed: the stop token was
appended and caught only by the text matcher. The resume now hands mlx-lm
the stashed matcher position through a one-shot StopSequences wrapper.

Greedy-identity tests cover stop sequences spanning one and two pauses,
held stop prefixes, text and parser stops completed by the pending token,
parser tool-call state, the thinking budget, repetition penalty context
and the max_tokens budget over two pauses.
With no prefill to park, the enforcer now pauses one decoding row through
request_decode_pause: the largest live KV first, the newest arrival on
ties, the oldest admitted request only when it is the sole candidate.
The pause is tracked as the draining victim; its status stays pending
until the pause ran and its exact chain left the SSD write buffers, then
one settle poll passes before another victim is chosen. Only when no row
is pausable, or a pause was declined, does the single-victim abort run.
Emergency pressure still aborts everything.

A pause that fails before the row leaves the batch (extract, store, pin
or any exception) keeps the row decoding untouched, unpins and deletes
the chain found by its domain hashes, and marks the request so it is not
chosen again. A failure after the pending token streamed ends the request
with decode_pause_failed. A parser or text stop on the pending token also
deletes the chain it stored.
…re a pause

A singleton Lightning MTP row was excluded from decode pause because its
pending token lives in the speculative queue. The pause now asks
handoff_singleton_mtp_for_pause for the late-join handoff: it waits
while more than one committed token is queued (the pause stays pending,
bounded by _DECODE_PAUSE_MAX_DEFERRED_STEPS), then leaves the batch in
the standard invariant, so the exact-prefix store and its offset guard
apply unchanged. A failed handoff declines the pause and the row keeps
decoding. Batched Lightning MTP, DFlash, VLM-MTP and SpecPrefill stay
excluded.

The handoff is checked on the real patched BatchGenerator with the MTP
suite's CountingModel: the KV holds exactly prompt plus streamed tokens,
and a resume on a fresh generator with MTP on matches an uninterrupted
MTP run.
A parked head (prefill-parked or decode-paused) now resumes once the
estimated free memory under the admission line covers its need plus a 2%
margin, instead of after a fixed streak of ok pressure polls.

- Need: a paused decode is priced at the KV of its final length (saved
  context, kickoff, remaining max_tokens) plus one decode transient; a
  parked prefill at the KV of prompt plus max_tokens plus the prefill
  transient of what is left to compute.
- Free: admission line minus current usage minus the KV that running
  prefills still have to allocate.
- The head never resumes on hard pressure; the stale-monitor and
  nothing-admitted escapes stay. The head-of-line hold is the reservation:
  nothing newer is admitted while the head waits, FIFO among parked.
- Without an estimate the ok-poll rule and the max-hold escape remain.
- Logs the wait (rate-limited) and the fit that released the head.
…hunked path

A request with any image in its history carried fused embeddings and always
prefilled in the synchronous external loop, even when every media token sat
inside the restored prefix. It froze concurrent decode and could not be
parked.

The VLM engine now records Request.vlm_media_end, the token index after the
last image, video or audio placeholder. Behind the
scheduler.media_text_suffix_chunked setting (default off), admission routes such a request to the text path when the
cached prefix reaches the media end, the mRoPE delta was captured, there is
no atomic media prefix or SpecPrefill, more than one token is left, and every
suffix position equals k + delta on all planes. The delta is bound before the
first chunk; the embeddings stay on the request for an OOM requeue or a park
re-admit. The decode text-position proof is kept only for a zero delta, the
suffix is priced like a media request, and a text-suffix request is parkable.
… enforcer

The admission features that follow (the never-fits 400 with the capacity
numbers and header, the fits-later wait with the solo admission of a lone
head, the progress-based admission-stall clock, and the external-loop
prefill exemption at hard pressure) plan against a fixed memory budget.
That budget only holds when the operator pinned the ceiling and expects
memory pressure, so each of them is gated by this setting from its first
commit and main's admission is unchanged unless it is on.

- memory.memory_scheduling (OMLX_MEMORY_SCHEDULING): "auto" (default) is on
  when the guard is on and an explicit ceiling is set (custom tier with a
  ceiling > 0); "on" forces it on but still needs the guard (warning
  otherwise); "off" forces it off.
- The enforcer resolves it at startup and on every live change of the mode,
  guard, tier or ceiling, logs "Memory scheduling: on (explicit ceiling
  48.0 GB)" or the reason it is off, and propagates it to every scheduler
  (Scheduler._memory_scheduling, off until an enforcer sets it).
- Exposed in the admin global settings (GET and live POST).

Nothing reads it yet, so behaviour is unchanged.
The settings page's tier previews (preview_tier_ceilings, run on every
GET /admin/api/global-settings) build one throwaway enforcer per tier with
the default mode, and each logged "Memory scheduling: off (no explicit
memory ceiling ...)". Those lines read as the live enforcer turning off
after admin saves; it never changed. Only an enforcer that drives an engine
pool logs its state now.

An explicit memory_scheduling POST logs the resolved state even when it is
unchanged and re-propagates it. GET /admin/api/global-settings reports the
live state as memory.memory_scheduling_effective (enabled and reason, null
without an enforcer), and the POST response carries it.
…wait

The preflight compared a request against current usage, so a request
that would fit once the running ones finish was rejected. The decision
is now split.

- Never fits alone: weights + exact KV of prompt plus max_tokens +
  prefill transient over the capacity line (the tighter of the admission
  line and the prefill safety cap) raises ContextExceedsCapacityError,
  whatever the current usage. HTTP 400 keeps the existing envelope and
  adds omlx_code context_exceeds_capacity, required/capacity/weights
  bytes, kv_bytes_per_token, the requested tokens,
  max_viable_context_tokens and retryable: false. No eviction is asked
  for it; the in-stream admission ends it with the same structured error.
- Fits alone but not now: the route preflight lets it queue while other
  work is admitted or queued, and the in-stream admission keeps it at the
  head until the admitted rows free memory. With nothing admitted, or
  without an estimate, the old rejection applies.
- Capacity hint: GET /v1/omlx/capacity?model=<id> returns the same
  numbers plus free_bytes_now (inference API key, never loads a model),
  and chat completions carry a cached X-oMLX-Max-Context-Tokens header.
- Weights are summed once from the model's parameter arrays; max_tokens
  is threaded from the chat and completion preflights.

On current main: no text_only parameter (jundot#3482); the capacity estimate
prices the transient through the shared admission estimate, so it follows
the execution-route predicate. The fits-later wait sits behind upstream's
hot-cache credit (jundot#4252): only a request that is over the line after the
credit waits or is rejected.

All of this is memory scheduling (memory.memory_scheduling): with it off,
the default for a stock install, there is no capacity estimate, so the
route preflight and the in-stream admission keep the current-usage
rejection, chat completions carry no header, and the capacity endpoint
answers available: false with memory_scheduling: "off" and the reason.
Four fixes to the capacity gate:

- The route preflight priced an omitted max_tokens as 0 output tokens
  while the in-stream check used the resolved value. The completion route
  now resolves max_tokens before its preflight, and engine preflights fall
  back to the engine default (ENGINE_DEFAULT_MAX_TOKENS) a direct call runs
  with.
- The route preflight let a request wait whenever anything was queued.
  Both checks now share one predicate: fits later only while admitted rows
  hold memory that comes back.
- A deferred request kept its restored prefix and block-table refs while
  it waited. The defer path now releases them (PagedCacheManager
  release_block_table keeps the blocks findable) and the re-admission
  repeats the lookup.
- Unknown weights fell back to the monitor's process baseline and were
  cached for good. Unknown weights now mean no estimate, are never cached,
  and never reject as never-fits.
…e deferred head

Two fixes to the fits-later wait.

- The block-table release of a deferred admission can wait behind an
  in-flight prefill commit. It was keyed only by request id, so if it ran
  after a re-admission it would release the new table. It now captures
  the attempt's table: release_block_table(rid, table=...) gives back that
  table's refs and drops the entry only while it is still that table.
  A deferred head whose release still waits keeps the head-of-line hold
  instead of being set aside for backfill.
- A deferred head gave back its restored prefix and was retried on the
  next step, restoring the prefix from SSD again every step while memory
  stayed tight. It now retries only when the memory picture changed: an
  admitted row left (finished, aborted or paused), free memory rose by more
  than 2% of the admission line, or an exponential backoff expired (0.25 s
  doubling per deferral, capped at 4 s). The release stays, FIFO and the
  hold are unchanged. Rig: 10 restores in 10 unchanged steps before, 1 after.
…gate

VLMModelAdapter keeps the mlx-vlm model in _vlm_model, which
nn.Module.parameters() skips, so the scheduler summed 0 bytes of weights,
capacity_snapshot returned None and the never-fits gate and capacity hint
were dead on VLMBatchedEngine. Unwrap the adapter (and the VLM-MTP proxy)
and count each array once.

Tests use a tiny real mlx-vlm Qwen3.5 model behind the real adapter: the
capacity is available, kv_bytes_per_token prices the TurboQuant prefill
peak, quantized scales and biases count, and max_tokens 2,000,000 reaches
the gate unclamped and is rejected as never-fits.
…ed prefill

Upstream jundot#4383 reports only genuine prefix-cache hits as cached tokens:
prefill work a request computed itself and kept across a pause is counted in
prefill_resumed_tokens and subtracted from usage.

A prefill park drops the live cache and the re-admission lookup restores the
blocks the request committed itself, so usage counted that resumed work as a
cache hit. The park now records the prompt tokens its lookups found
(park_cache_hit_tokens); every later lookup sets prefill_resumed_tokens to
the restored tokens beyond them. A fits-later deferral that releases the
restore also clears prefill_resumed_tokens, as upstream's resets do.
…ut thrashing

Under forced memory pressure, a lone 130k request decoding over the hard
watermark was paused, resumed on the next step by the park hold's
nothing-admitted escape (which never asked whether it fit), paused again,
and aborted once its park budget (3/3) ran out. No memory-aware resume
line was logged in any run.

- A parked head is measured whenever it has an estimate. Beside admitted
  work it resumes only under the admission line minus 2% and the hard
  watermark minus 5%.
- Anti-thrash: a head parked or paused twice within 60 s waits, even when it
  fits, for an admitted row to leave or free memory to rise by 5%.
- With nothing admitted, a head that fits only under the ceiling, keeps being
  paused while alone, or waited PARK_MAX_HOLD_S resumes as the solo request:
  nothing else is admitted beside it, and the enforcer neither pauses nor
  aborts it below the emergency threshold while every other engine is idle.
  The emergency brake still aborts it.
- Decode pauses get their own budget, max_decode_pauses_per_request
  (default 8, OMLX_MAX_DECODE_PAUSES_PER_REQUEST): a pause keeps every
  generated token, while the abort after an exhausted budget loses them.

Real-rig tests with the real enforcer replay the readings of that run:
every request completes with its uninterrupted greedy output and no abort.
Upstream's _make_enforcer now pins _get_abort_limit_bytes to the ceiling
(jundot#4312), and the emergency brake measures against that physical cap. The
resume-thrash fixture took its physical cap from the host before (120 GB on
a 128 GB machine), so its solo line depended on the machine: with the cap at
the ceiling, the prefill safety cap binds and the lone request never resumes
solo.

The fixture now keeps the physical cap out of the way (200 GB), as the
scheduler-unit fixture in the same file does, and the emergency-brake case
pins it to the ceiling, the line it tests.
…ncy abort-all

In a real-model image-decode run, at the end of a lone 130k image prefill
usage reached 35.3 GB, over the 33.6 GB hard watermark but under the 42 GB
ceiling, so the emergency brake did not fire. The non-emergency path found
nothing to park or pause, the single-victim selection found no live request
(the external prefill is neither running nor a chunked prefill, queued
requests hold no KV), and the enforcer fell back to abort-all: every request
was lost and aborting the queued ones freed nothing.

- A request in the external prefill loop with nothing else admitted runs
  alone: the enforcer neither pauses nor aborts it below the emergency
  threshold. A decoding row beside it is paused instead.
- With no live request to abort, the non-emergency path aborts nothing.
- Emergency pause-first: beyond the ceiling, one decode pause of the largest
  pausable row that brings usage back under it comes before abort-all,
  waited on for at most two polls while usage does not grow.
- With the park feature on, a media prefill beside admitted work whose
  estimated peak crosses the hard watermark minus 5% waits at the head
  instead of spiking past it.

Tests poll the real enforcer while the real scheduler's thread sits inside
the external prefill.

The external-loop exemption is memory scheduling (memory.memory_scheduling):
with it off, the default for a stock install, a lone external-loop prefill
is not reported as solo and the enforcer's hard path stays main's.
…solo read thread-safe

- The no-live-victim relief skipped abort-all without re-checking the
  level. Usage that grew past the emergency line during the poll now gets
  the last resort: one decode pause first when it gets back under the
  ceiling, then abort-all. The relief stays below the emergency level
  only. The re-check does not count another over-ceiling poll.
- memory_pressure_solo_request (enforcer thread) cleared _solo_request_id
  for a finished request while the MLX thread could be marking a new one.
  The enforcer read is now read-only; only the scheduler thread
  (_solo_holds) clears the mark.
…d on purpose

The admission-stall clock started when the head first met memory pressure
and kept running while a solo request decoded (the solo hold breaks before
the stall check) and while another request prefilled chunk after chunk. In
a real-model run the first check after the solo run failed the third request
("memory pressure persisted for 90.6s (store_cache_backpressure)"; image
prefill: 67.5s, admission_paused) although the server progressed all along.

The clock now measures time without progress: a token emitted, a prefill
chunk processed, an external prefill finished, a request admitted or a
store-cache write drained restarts it. Without progress the head still fails
after 60 s. While a solo request runs, a fits-later head backs off, or a
parked or decode-paused request waits, the bound is
scheduler.admission_no_progress_timeout_s (OMLX_ADMISSION_NO_PROGRESS_TIMEOUT_S,
default 600 s), so a genuine deadlock surfaces with memory_admission_stalled
and no_progress_seconds. Store-cache backpressure is not a failure while the
writer drains. "Admission waiting for memory: <reason>; <n> request(s)
progressing" is logged every 30 s per head.

The progress clock is memory scheduling (memory.memory_scheduling): with it
off, the default for a stock install, the head fails 60 s after it first
blocked, whatever else progresses, with main's message and metadata (no
no_progress_seconds) and no wait log.
…tead of rejecting it

Two real-model image-prefill runs at a 46 GB ceiling: when the request
ahead finished, the next image request reached the in-stream preflight with
nothing admitted. It fits alone by estimate, but the usage reading also
held memory no admitted request owns (queued requests' vision embeddings
and other residue, 2.9-4.3 GB over the weights), so current + KV +
transient crossed the admission line by under 1 GB (33.01 > 32.79 GB,
33.23 > 32.54 GB) and the prefill memory guard rejected it, with the 46 GB
ceiling far above its peak.

A parked head in that position already resumes alone (solo). A queued head
now follows the same rule: with nothing admitted and no store write pending,
a request that fits alone and whose peak stays under the solo line (ceiling
and prefill safety cap minus 2%) is admitted as the solo request. Nothing is
admitted beside it and the enforcer leaves it to the emergency brake. The
route preflight lets it queue. Over the solo line, or with park off, the
older rejection applies.

The solo admission needs the capacity estimate, so it is memory scheduling
(memory.memory_scheduling) as well: with it off, the default for a stock
install, a lone head gets the current-usage rejection as on main.
…ale reading

In an image-decode run under forced memory pressure (42 GB ceiling), req1
fits alone and was deferred while req0 ran. Both prefill-eviction retries
were spent in that wait (retry=1/2, insufficient_headroom). When req0
finished, req1 was re-checked as the lone head 9 ms after req0's SSD
write-through was dispatched, on a reading that still held pooled Metal
buffers and the finished request's KV (current 30.27 GB, ~40.05 GB peak
over the 31.28 GB line). With no retry left and the stale estimate over the
solo line, the prefill memory guard rejected it. 0.1 s later the ladder
freed 6.21 + 2.55 GB for req2.

- The eviction budget is per admission attempt: when a fits-later wait
  ends (a row it waited on left or a store write it waited on drained) or
  a park resumes, request.prefill_eviction_retries restarts at 0. A retry
  on backoff beside the same rows keeps the spent budget, so the ladder
  does not run on every retry. The deferral record stays (the head keeps
  its hold) with the current picture, so the reset happens once.
- A lone head (nothing admitted) that fits alone and is over the admission
  line or the safety cap returns the pooled buffers on the scheduler thread
  and is re-measured before any decision.
- The fits-later wait also holds while the store-cache pipeline still owns
  a finished request's KV (gate in-flight or a pending deferred remove);
  the deferred head retries when a write drains. The run above shows the
  need: the second ladder pass found another 2.55 GB in the pool within
  ~170 ms of the finish.

With nothing admitted, nothing draining and nothing reclaimed, the older
rejection still applies; a request that never fits still gets the 400.
…ain only when it blocked

The fits-later wait ended, and the eviction budget reset, whenever the
store-job count fell below the count recorded at deferral, even while the
admitted rows the head waited on still ran. An unrelated earlier request's
write draining then gave the head fresh ladder passes beside the same rows.

A store drain now ends the wait only for a head that waited on no admitted
row (a lone head waiting on the write). Beside rows it waits on, only one
of them leaving ends the wait. The stale-reading case stays covered: the
waited-on row leaving ends the wait and renews the budget.
With memory scheduling off and park on, a parked head still resumes as the
solo request (park only), but the head queued behind it got upstream's
fixed 60 s clock and failed while the solo request was still emitting
tokens, as in the forced memory-pressure run.

The admission-stall clocks now measure time without progress, with the
600 s bound for deliberate holds, whenever memory scheduling is on or a hold
the park feature created is active: a parked or decode-paused request
running solo or waiting in the queue. With park off such holds never exist,
so upstream's fixed clock is unchanged. memory_scheduling keeps gating the
never-fits 400 with the capacity numbers and header, the fits-later wait,
the solo admission of a lone head and the external-prefill solo.
Upstream's route preflight credits the hot cache a request would release
(jundot#4252), and the in-stream eviction ladder releases it, so main admits and
runs a request the hot cache can make room for. The never-fits gate compared
the request against the capacity line without that credit and answered with
a permanent 400 (retryable: false) for the same request.

The gate checks (route preflight, the eviction request and the in-stream
admission) now count the same credit when a request is over the line
otherwise, with the request's own prefix bounded by the exact KV of its
context, as upstream does. The 400 body, the capacity endpoint and the
X-oMLX-Max-Context-Tokens header stay credit-free. With memory scheduling
off there is no capacity estimate and nothing changes.
…editing the request

The never-fits gate subtracted the releasable hot cache from the request's
required bytes, while max_viable_context_tokens and the 400 body were
priced against the credit-free line. One estimate could say fits_alone above
its own max viable context, and the 400 named a boundary the gate did not use.

The credit belongs on the line: the scheduler's limits are the ceiling minus
the hot-cache reservation, and upstream's eviction ladder releases cold
blocks and raises them (jundot#4252), so main runs a request the released hot
cache makes room for. The gate estimate now carries capacity_bytes = line +
credit (the request's own prefix still protected), fits_alone compares
required_bytes with it alone, and max_viable_context_tokens is searched
under the same line. The 400 message names the credited hot cache. The
capacity endpoint and the header stay credit-free; the current-usage checks
keep main's credit.
With memory scheduling off and park on, the stall checks switch between the
progress clock (while a park hold is active) and upstream's fixed clock on
every call. The fixed clock ran from when the head first blocked, so a head
still blocked when the hold ended jumped back to that time and failed at
once on the 60 s timeout, for time it spent waiting through the hold.

The scheduler now records when the progress clock turns off, and the fixed
clock of a blocked head never starts before that moment: the head gets the
full upstream timeout after the hold ends. A head that blocks later keeps
upstream's clock unchanged. Covers the memory and store-cache stalls.
@jundot

jundot commented Oct 14, 2026

Copy link
Copy Markdown
Owner

I'm closing this PR as part of the pause-and-resume stack replaced by #4509. I've posted the replacement's scope and remaining proposals in the discussion update.

@jundot jundot closed this Oct 14, 2026
@e-Evolution
e-Evolution deleted the stack/s9-scheduling-followups branch November 6, 2026 22:02
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.

2 participants