From 8ba507811d05a9761ef98ed1728b6c103309400a Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Thu, 1 Oct 2026 13:47:55 -0600 Subject: [PATCH 01/18] feat(scheduler): commit completed prefill blocks to the prefix cache 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. --- docs/TESTING.md | 6 + omlx/cache/prefix_cache.py | 12 +- omlx/scheduler.py | 314 ++++++++++ .../test_scheduler_prefill_progress_commit.py | 549 ++++++++++++++++++ 4 files changed, 879 insertions(+), 2 deletions(-) create mode 100644 tests/test_scheduler_prefill_progress_commit.py diff --git a/docs/TESTING.md b/docs/TESTING.md index f39b692391..aeb9da1a04 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -228,3 +228,9 @@ Run `python -m pytest -q tests/integration/test_server_endpoints.py -k structure Run `python -m pytest -q tests/test_qwen4_qsa_decode_gather.py -k "batch_bank or batch_gather"` to check the batched QSA paths. The row-bank cases drive one attention layer through right-padded chunked prompt prefill, decode, verify windows, ragged vector rollback, reorder and drop filters, extend, trim and state restore, and require layer outputs and cache state to be bit-identical with fresh per-row indexer caches. The gathered cases compare batched decode steps and verify windows with the dense masked path: outputs allclose, cache state identical, every query bounded to the QSA budget plus its tail, and each fail-closed case kept on the dense path. Both groups include the served ratio 4 / top-k 512 geometry. For a real-server comparison, use the same model, prompts and cache state on main and the branch, with sessions of different lengths well past the QSA crossover (e.g. a 100K shared prompt plus 2K unshared tokens per session). Report aggregate decode while every stream is decoding, per batch size, with Lightning MTP on and off, and check a temperature-0 cold/warm identity and a multi-session codeword fan-out with prompts of different lengths. + +# Incremental prefill commit tests + +Run `python -m pytest -q tests/test_scheduler_prefill_progress_commit.py tests/test_settings.py -k "prefill_progress or commit"` to check `scheduler.prefill_progress_commit_blocks` (also `OMLX_PREFILL_PROGRESS_COMMIT_BLOCKS`; 0 = off, the default). The cases drive the real chunked and external prefill loops on a small initialized Qwen3.5 hybrid model (inline and split-GDN snapshots) and a small dense model, against real paged-SSD, boundary-snapshot and prefix stores, and compare restored-prefix logits with a cold forward pass. They cover commits every N blocks, a request aborted mid-prefill whose same-prompt re-issue resumes from the last committed boundary, completion after commits (same stored prefix, no duplicate blocks or leftover snapshot markers), a commit window longer than the restored prefix, TurboQuant windows matching whole-prefix conversion bit for bit, the memory-pressure skip, and the cold retry after a prefill memory failure. + +Mocked tests do not replace hardware validation: with a real model, abort a long prompt mid-prefill (for example with a low memory ceiling and two concurrent prompts), re-issue it, and check that the log reports a prefix cache restore at the last committed boundary instead of a full prefill. diff --git a/omlx/cache/prefix_cache.py b/omlx/cache/prefix_cache.py index 8cf3395a0e..d4f9c8e5c4 100644 --- a/omlx/cache/prefix_cache.py +++ b/omlx/cache/prefix_cache.py @@ -899,6 +899,7 @@ def store_cache( hot_cache_write_back: bool = True, _store_exact_terminal: bool = False, _store_tail_terminal: bool = False, + cache_covers_suffix_only: bool = False, ) -> BlockTable | None: """ Store computed cache for future reuse. @@ -926,6 +927,11 @@ def store_cache( ordinary prefix matching. _store_tail_terminal: Persist the trailing partial block as a tail block; ``tokens`` must end on a snapshot in ``boundary_snapshots``. + cache_covers_suffix_only: ``cache_data`` holds only the tokens + after the request's existing block table (an incremental + commit during prefill), never the whole sequence. Without this + a window longer than the stored prefix is indistinguishable + from a full-sequence cache. Returns: BlockTable for the stored cache, or None on failure @@ -1356,8 +1362,10 @@ def store_cache( # BatchGenerator.extract_cache() currently returns full-sequence cache. # When existing_tokens > 0, slicing with relative indices would save # wrong KV ranges for new blocks and corrupt future cache hits. - cache_uses_global_indices = existing_tokens > 0 and cache_seq_len >= ( - existing_tokens + 1 + cache_uses_global_indices = ( + not cache_covers_suffix_only + and existing_tokens > 0 + and cache_seq_len >= (existing_tokens + 1) ) if cache_uses_global_indices: cache_start = global_start diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 32c941e351..6502d54dd9 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -1335,6 +1335,12 @@ def _is_turboquant_kv_family_cache(cache_obj: Any) -> bool: ) or _is_turboquant_kv_cache(cache_obj) +def _prefill_commit_blocks(config: Any) -> int: + """``prefill_progress_commit_blocks`` of a config, 0 when unset or invalid.""" + value = getattr(config, "prefill_progress_commit_blocks", 0) + return value if isinstance(value, int) and value > 0 else 0 + + class _BoundaryStoreUnavailable(Exception): """No boundary-aligned snapshot exists for non-sliceable cache state. @@ -1845,6 +1851,12 @@ class SchedulerConfig: decode_fairness: bool = True # Set by the engine when MoE expert offload wrapped the model. moe_offload_active: bool = False + # Commit completed prefill blocks to the prefix cache every N blocks while + # a prompt is still being prefilled (0 = off, blocks are stored only when + # the request finishes). A request aborted mid-prefill then keeps its + # completed blocks, and a re-issue of the same prompt resumes from the last + # committed block boundary instead of prefilling from token zero. + prefill_progress_commit_blocks: int = 0 # Paged cache settings (internal defaults) paged_cache_block_size: int = 256 # Tokens per block @@ -2208,6 +2220,9 @@ def __init__( "max_rows": 0, "failures": 0, } + # request_id -> (future, committed token count) of the in-flight + # incremental prefill commit (see _commit_prefill_progress). + self._prefill_commits: dict[str, tuple[concurrent.futures.Future, int]] = {} self.requests: dict[str, Request] = {} # All requests by ID self.finished_req_ids: set[str] = set() # Recently finished self._generation_overflow_recovery_ids: set[str] = set() @@ -2758,9 +2773,15 @@ def _async_store_cache_worker( extra_key_token_start: int | None, extra_key_ranges: list[tuple[int, tuple[Any, ...]]] | None, hot_cache_write_back: bool = True, + incremental_commit: bool = False, ) -> None: """Run store_cache + paged_cache cleanup off the inference thread. + ``incremental_commit`` marks a mid-prefill commit: ``cache_to_store`` + holds only the tokens after the request's existing block table, and + the table stays alive so the next commit (or the final store) extends + it instead of re-storing from token zero. + Pre-conditions enforced by the caller (_cleanup_finished): - mx.eval() (a FULL, blocking eval — NOT async_eval) was called on the inference thread for all KV cache arrays in cache_to_store, so @@ -2793,6 +2814,7 @@ def _async_store_cache_worker( threading.RLock so concurrent access from main and worker is safe. """ self._store_cache_thread_id = threading.get_ident() + window_kwargs = {"cache_covers_suffix_only": True} if incremental_commit else {} try: # Hold _mx_buffer_access_lock across the worker's mx-buffer # access. store_cache eventually drives _extract_tensor_bytes, @@ -2817,6 +2839,7 @@ def _async_store_cache_worker( extra_key_token_start=extra_key_token_start, extra_key_ranges=extra_key_ranges, _store_tail_terminal=store_tail_terminal, + **window_kwargs, ) else: block_table = self.block_aware_cache.store_cache( @@ -2830,7 +2853,10 @@ def _async_store_cache_worker( extra_key_ranges=extra_key_ranges, hot_cache_write_back=False, _store_tail_terminal=store_tail_terminal, + **window_kwargs, ) + if incremental_commit: + return if block_table is None and self.paged_cache_manager is not None: block_table = self.paged_cache_manager.get_block_table(request_id) if block_table and self.paged_cache_manager is not None: @@ -4485,6 +4511,10 @@ def _chunk_route(n_tokens: int, cache_tokens: int) -> bool: self._emit_prefill_tail_snapshot( request, prompt_cache, total_tokens ) + if vlm_embeds is None: + Scheduler._commit_prefill_progress( + self, request, prompt_cache, base_size + processed_tokens + ) Scheduler._check_post_prefill_memory( self, @@ -6751,6 +6781,9 @@ def _finish_prefill_row(self, plan: _PrefillChunkPlan) -> None: self._emit_prefill_tail_snapshot( state.request, state.cache, total_tokens ) + Scheduler._commit_prefill_progress( + self, state.request, state.cache, state.base_size + state.tokens_processed + ) # Progress callback so the admin UI prefilling list advances during # chunked prefill. _do_external_prefill calls _on_prompt_progress @@ -7607,6 +7640,260 @@ def _emit_prefill_boundary_snapshot( ), ) + def _prefill_commit_blocked_by_pressure(self) -> bool: + """True while memory sits at or above the soft limit. + + A commit slices KV, quantizes it and materializes a snapshot, all of + which allocate; doing that when the guard is already struggling would + add to the pressure it is meant to survive. The hard limit lies above + the soft one, so this also covers hard pressure. + """ + limit = self._memory_limit_bytes + if limit <= 0: + return False + try: + return self._current_usage_bytes() >= limit + except Exception: + return True + + def _prefill_commit_window( + self, prompt_cache: list[Any], start: int, end: int + ) -> list[Any] | None: + """Detached cache list holding KV tokens ``[start, end)`` of a prefill. + + KV layers become windowed copies, TurboQuant layers get the same + conversion the finished request would receive, and non-sliceable layers + pass through untouched. Returns None for a layout whose window cannot + be stored faithfully (composite or unknown sliceable caches). + + The final store quantizes the whole fp16 prefix with the same + per-vector codec (norm, fixed-seed rotation, midpoints), so converting + a window yields byte-identical blocks. The layer signature is stamped + by the same ``_apply_turboquant_kv_convert`` rules. + """ + from mlx_vlm.turboquant import TurboQuantKVCache, _slice_state_range + + window: list[Any] = [] + for layer in prompt_cache: + if type(layer) in (_MLXKVCache, _vlm_cache.KVCache): + if layer.keys is None or layer.offset < end: + return None + piece = type(layer)() + piece.keys = layer.keys[..., start:end, :] + piece.values = layer.values[..., start:end, :] + piece.offset = end - start + window.append(piece) + elif type(layer).__name__ == "TurboQuantKVCache": + # A restored TurboQuant prefix keeps quantizing in place, so + # the window is a slice of the packed state. + if layer.keys is None or layer.offset < end: + return None + piece = TurboQuantKVCache( + bits=layer.bits, + seed=layer.seed, + key_bits=layer.key_bits, + value_bits=layer.value_bits, + ) + piece.key_codec = layer.key_codec + piece.value_codec = layer.value_codec + piece.keys = _slice_state_range(layer.keys, start, end) + piece.values = _slice_state_range(layer.values, start, end) + piece.offset = end - start + window.append(piece) + elif type(layer).__name__ in _KNOWN_SLICEABLE_CACHE_TYPES or type( + layer + ).__name__ in ("CacheList", "BatchRotatingKVCache"): + return None + else: + window.append(layer) + if self._turboquant_kv_bits is not None and self._turboquant_eligible( + prompt_cache + ): + self._apply_turboquant_kv_convert(window) + return window + + def _reap_prefill_commit(self, request_id: str) -> None: + """Retire a finished commit: drop snapshot markers it consumed. + + Runs on the inference thread. The commit worker moves (split-GDN) or + reads (inline) the staged snapshot of every committed boundary, so + their markers must not reach the final store, which would try to load + a moved file. A failed commit leaves them in place for the next try. + """ + pending = (getattr(self, "_prefill_commits", None) or {}).get(request_id) + if pending is None: + return + future, committed_tokens = pending + if not future.done(): + return + del self._prefill_commits[request_id] + try: + ok = bool(future.result()) + except Exception: + ok = False + if not ok: + return + snapshots = self._boundary_cache_snapshots.get(request_id) + if snapshots: + for token_count in [tc for tc in snapshots if tc <= committed_tokens]: + del snapshots[token_count] + + def _settle_prefill_commits(self, request_id: str) -> None: + """Wait for an in-flight commit before its request is torn down. + + Teardown releases the block table and removes the snapshot directory, + which the commit worker is still reading. Commits are a few blocks, so + the wait is short; the blocks it stores stay in the prefix cache. + """ + pending = (getattr(self, "_prefill_commits", None) or {}).get(request_id) + if pending is None: + return + try: + pending[0].result(timeout=60) + except Exception as e: + logger.warning("Prefill commit for %s did not settle: %s", request_id, e) + self._reap_prefill_commit(request_id) + self._prefill_commits.pop(request_id, None) + + def _commit_prefill_progress( + self, request: "Request", prompt_cache: list[Any], total_tokens: int + ) -> None: + """Make completed prefill blocks durable while the prompt is prefilling. + + Every ``prefill_progress_commit_blocks`` completed blocks, store them in + the prefix cache under the request's own block table, which stays alive + so the next commit and the final store extend it. A request aborted + later keeps these blocks: a re-issue of the same prompt matches them + and resumes at the last committed boundary. + """ + commit_blocks = _prefill_commit_blocks(getattr(self, "config", None)) + if commit_blocks <= 0: + return + try: + self._commit_prefill_progress_unchecked( + request, prompt_cache, total_tokens, commit_blocks + ) + except Exception as e: + # Durability is best effort; it must never fail the prefill. + logger.warning( + "Prefill progress commit failed for %s: %s", request.request_id, e + ) + + def _commit_prefill_progress_unchecked( + self, + request: "Request", + prompt_cache: list[Any], + total_tokens: int, + commit_blocks: int, + ) -> None: + rid = request.request_id + block_size = self.config.paged_cache_block_size + if ( + block_size <= 0 + or self.block_aware_cache is None + or self.paged_cache_manager is None + or self.paged_ssd_cache_manager is None + or self._store_cache_executor is None + ): + return + # Prompts that are not a plain token prefix cannot be keyed by token. + if ( + getattr(request, "vlm_extra_keys_for_cache", None) + or getattr(request, "vlm_extra_key_ranges_for_cache", None) + or getattr(request, "specprefill_indices", None) is not None + or self._specprefill_active_request_id == rid + ): + return + prompt = request.prompt_token_ids + aligned = min(total_tokens, len(prompt)) // block_size * block_size + + self._reap_prefill_commit(rid) + if rid in self._prefill_commits: + return # previous commit still running + table = self.paged_cache_manager.get_block_table(rid) + existing = table.num_tokens if table else 0 + if existing % block_size or (aligned - existing) // block_size < commit_blocks: + return + if self._prefill_commit_blocked_by_pressure(): + return + + window = self._prefill_commit_window(prompt_cache, existing, aligned) + if window is None: + if not getattr(self, "_prefill_commit_layout_logged", False): + self._prefill_commit_layout_logged = True + logger.info( + "Prefill progress commit disabled for this cache layout " + "(composite or non-standard sliceable layers)" + ) + return + tokens = list(prompt[:aligned]) + provider = None + with mx.stream(self._stream): + extracted, model_cache_config = self._extract_cache_states(window) + if _prompt_cache_needs_snapshots(prompt_cache): + override = self._get_boundary_store_override(rid, tokens) + if override is None: + return + tokens, boundary_cache, _, provider = override + if ( + getattr(provider, "tail_terminal_token_count", None) is not None + or len(tokens) <= existing + ): + return + extracted = self._merge_boundary_with_full_cache( + boundary_cache, extracted + ) + arrays = self._collect_arrays_from_extracted_cache(extracted) + if provider is not None: + for snapshot_cache in provider.iter_in_memory_extracted(): + arrays.extend( + self._collect_arrays_from_extracted_cache(snapshot_cache) + ) + if arrays: + # Concrete on this thread before the worker slices them (MLX + # streams are thread-local; see _async_store_cache_worker). + mx.eval(*arrays) + + future = self._store_cache_executor.submit( + self._commit_prefill_worker, + rid, + tokens, + extracted, + model_cache_config, + provider, + ) + self._prefill_commits[rid] = (future, len(tokens)) + logger.debug( + "Committing prefill progress for %s: %d -> %d tokens", + rid, + existing, + len(tokens), + ) + + def _commit_prefill_worker( + self, + request_id: str, + tokens: list[int], + window_cache: list[Any], + model_cache_config: Any | None, + snapshots: Any | None, + ) -> bool: + """Store a committed prefill window; True when the table covers it.""" + self._async_store_cache_worker( + request_id, + tokens, + window_cache, + model_cache_config, + snapshots, + None, + None, + None, + True, + incremental_commit=True, + ) + table = self.paged_cache_manager.get_block_table(request_id) + return bool(table is not None and table.num_tokens >= len(tokens)) + def _resolve_generation_prompt_start(self, request: "Request") -> None: """Locate the generation prompt; accept it only if its tokens end the prompt.""" suffix = getattr(request, "generation_prompt_text", None) @@ -10182,6 +10469,23 @@ def _model_has_unreconstructible_cache(self) -> bool: self._unreconstructible_cache_model = result return result + def _retry_prefills_cold_after_oom(self, request: Request) -> bool: + """Keep the cold retry that _requeue_or_fail_prefill promises. + + Re-attaching a cached prefix reproduced the oversized SDPA span that + failed the first attempt, so a request requeued after a prefill memory + failure prefills from token zero. With incremental commits enabled the + failed attempt leaves committed blocks in the prefix cache, which would + otherwise be attached here; a client re-issue still resumes from them. + Gated on the setting so the default behavior is unchanged. + """ + retries = getattr(request, "prefill_oom_retries", 0) + return ( + isinstance(retries, int) + and retries > 0 + and _prefill_commit_blocks(getattr(self, "config", None)) > 0 + ) + def _prepare_prefix_cache_for_request(self, request: Request) -> None: if request.request_id in self._prefix_cache_prepared: return @@ -10197,6 +10501,7 @@ def _prepare_prefix_cache_for_request(self, request: Request) -> None: if ( self.block_aware_cache is not None and not self._model_has_unreconstructible_cache() + and not self._retry_prefills_cold_after_oom(request) ): # Use paged cache fetch_started = time.perf_counter() @@ -11429,6 +11734,9 @@ def _do_abort_request(self, request_id: str) -> bool: return False self._clear_request_admission_bookkeeping(request_id) + # Committed prefill blocks stay in the prefix cache; let an in-flight + # commit finish before the table and snapshots are released below. + self._settle_prefill_commits(request_id) # Remove from waiting queue if request.status == RequestStatus.WAITING: @@ -11616,6 +11924,7 @@ def _drop_boundary_snapshots_for_request(self, request_id: str) -> None: must do the same or every failure strands a snapshot set until process exit (#3226). """ + self._settle_prefill_commits(request_id) self._boundary_cache_snapshots.pop(request_id, None) if self._boundary_snapshot_store is not None: try: @@ -13397,6 +13706,7 @@ def _release_paged_cache_for_request(self, request_id: str) -> None: very memory pressure that triggered the rejection) and orphan ``_request_tables`` entries. """ + self._settle_prefill_commits(request_id) if self.block_aware_cache is not None: self.block_aware_cache.release_cache(request_id) elif self.paged_cache_manager is not None: @@ -13447,6 +13757,9 @@ def _cleanup_finished(self, finished_ids: set[str]) -> None: if finished_drafter is not None: finished_drafter.release_request(request_id) request = self.running.get(request_id) + # A mid-prefill commit still in flight must land (and retire its + # consumed snapshot markers) before the final store reads them. + self._settle_prefill_commits(request_id) # Store cache for future reuse (G2-async): submit to background # executor so the post-finish 28GB+ memcpy doesn't block response @@ -14173,6 +14486,7 @@ def collect(request: Request | None) -> None: for request in retry_candidates: request.generation_overflow_retries += 1 request_id = request.request_id + self._settle_prefill_commits(request_id) self._boundary_cache_snapshots.pop(request_id, None) if self._boundary_snapshot_store is not None: self._boundary_snapshot_store.cleanup_request(request_id) diff --git a/tests/test_scheduler_prefill_progress_commit.py b/tests/test_scheduler_prefill_progress_commit.py new file mode 100644 index 0000000000..6d2ba72f47 --- /dev/null +++ b/tests/test_scheduler_prefill_progress_commit.py @@ -0,0 +1,549 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Incremental prefill commit: completed blocks become durable during prefill. + +The tests drive the real chunked-prefill step against a small initialized +Qwen3.5 hybrid model (GatedDeltaNet + full attention) with real paged-SSD, +boundary-snapshot and prefix-cache stores, then compare restored-prefix logits +with a cold forward pass. +""" + +import concurrent.futures + +import mlx.core as mx +import pytest +from mlx_lm.models.qwen3_5 import Model, ModelArgs + +from omlx.cache.boundary_snapshot_store import BoundarySnapshotSSDStore +from omlx.cache.paged_cache import PagedCacheManager +from omlx.cache.paged_ssd_cache import PagedSSDCacheManager +from omlx.cache.prefix_cache import BlockAwarePrefixCache +from omlx.request import Request, SamplingParams +from omlx.scheduler import Scheduler, SchedulerConfig + +BLOCK = 4 + + +def _tiny_hybrid_model(): + return Model( + ModelArgs( + model_type="qwen3_5", + text_config=dict( + hidden_size=32, + intermediate_size=64, + num_hidden_layers=2, + num_attention_heads=2, + num_key_value_heads=1, + head_dim=16, + full_attention_interval=2, + vocab_size=32, + linear_num_value_heads=2, + linear_num_key_heads=2, + linear_key_head_dim=16, + linear_value_head_dim=16, + linear_conv_kernel_dim=4, + partial_rotary_factor=1.0, + ), + ) + ) + + +class _Rig: + """A scheduler wired to real stores, plus helpers to drive prefill.""" + + def __init__(self, tmp_path, tokenizer, *, split, commit_blocks, tq_bits=None): + mx.random.seed(11) + self.model = _tiny_hybrid_model() + self.scheduler = Scheduler( + model=self.model, + tokenizer=tokenizer, + config=SchedulerConfig( + paged_cache_block_size=BLOCK, + gdn_ssd_split_enabled=split, + chunked_prefill=True, + prefill_step_size=BLOCK, + prefill_progress_commit_blocks=commit_blocks, + ), + ) + self.paged = PagedCacheManager( + block_size=BLOCK, max_blocks=64, initial_blocks=64, model_name="tiny" + ) + kv_type = "TurboQuantKVCache" if tq_bits else "KVCache" + self.ssd = PagedSSDCacheManager( + cache_dir=tmp_path / "cache", + max_size_bytes=16 * 1024**2, + expected_model_name="tiny", + expected_num_layers=2, + expected_block_size=BLOCK, + expected_layer_cache_types=["ArraysCache", kv_type], + gdn_ssd_split_enabled=split, + ) + self.boundary = BoundarySnapshotSSDStore(tmp_path / "cache") + self.prefix = BlockAwarePrefixCache( + model=self.model, + paged_cache_manager=self.paged, + paged_ssd_cache_manager=self.ssd, + gdn_ssd_split_enabled=split, + ) + self.prefix.set_gdn_checkpoint_loader(self.boundary.load_file) + s = self.scheduler + s.paged_cache_manager = self.paged + s.paged_ssd_cache_manager = self.ssd + s._boundary_snapshot_store = self.boundary + s.block_aware_cache = self.prefix + s._store_cache_executor = concurrent.futures.ThreadPoolExecutor( + max_workers=1, thread_name_prefix="omlx-store-cache" + ) + if tq_bits: + s._turboquant_kv_bits = float(tq_bits) + s.refresh_ssd_layer_signature() + + def start(self, request_id, tokens): + request = Request( + request_id=request_id, + prompt=list(tokens), + sampling_params=SamplingParams(max_tokens=1), + ) + self.scheduler.add_request(request) + self.scheduler.waiting.clear() + request.remaining_tokens = list(tokens) + return request, self.scheduler._begin_prefill(request, list(tokens), None) + + def step(self, state, chunks): + done = False + for _ in range(chunks): + done = self.scheduler._step_prefill_chunk(state) + self.drain() + return done + + def drain(self): + """Wait for every in-flight store or commit on the store executor.""" + self.scheduler._store_cache_executor.submit(lambda: None).result(timeout=20) + + def close(self): + self.scheduler.shutdown() + + def table_tokens(self, request_id): + table = self.paged.get_block_table(request_id) + return table.num_tokens if table else 0 + + def probe(self, tokens): + """Prefix lookup a fresh request with the same prompt would perform.""" + table, remaining = self.prefix.fetch_cache("probe", list(tokens)) + return table, remaining + + +PROMPT = list(range(3, 20)) # 17 tokens -> 16 prefill tokens -> four blocks + + +@pytest.fixture(params=[False, True], ids=["inline-gdn", "split-gdn"]) +def split(request): + return request.param + + +def test_setting_off_stores_nothing_during_prefill(tmp_path, mock_tokenizer, split): + rig = _Rig(tmp_path, mock_tokenizer, split=split, commit_blocks=0) + try: + _, state = rig.start("r1", PROMPT) + rig.step(state, 3) + assert rig.table_tokens("r1") == 0 + table, remaining = rig.probe(PROMPT) + assert table is None + assert remaining == PROMPT + finally: + rig.close() + + +def test_commit_every_n_blocks_stores_completed_blocks(tmp_path, mock_tokenizer, split): + rig = _Rig(tmp_path, mock_tokenizer, split=split, commit_blocks=2) + try: + _, state = rig.start("r1", PROMPT) + rig.step(state, 1) + assert rig.table_tokens("r1") == 0 # one block done, below the threshold + rig.step(state, 1) + assert rig.table_tokens("r1") == 2 * BLOCK + rig.step(state, 1) + assert rig.table_tokens("r1") == 2 * BLOCK # third block waits for N=2 + rig.step(state, 1) + assert rig.table_tokens("r1") == 4 * BLOCK + finally: + rig.close() + + +def test_abort_mid_prefill_keeps_committed_blocks_for_a_reissue( + tmp_path, mock_tokenizer, split +): + rig = _Rig(tmp_path, mock_tokenizer, split=split, commit_blocks=2) + try: + _, state = rig.start("r1", PROMPT) + rig.step(state, 3) # blocks 1-2 committed, block 3 only in flight + assert rig.scheduler._do_abort_request("r1") + + table, remaining = rig.probe(PROMPT) + assert table is not None and table.num_tokens == 2 * BLOCK + assert remaining == PROMPT[2 * BLOCK :] + + restored = rig.prefix.reconstruct_cache(table) + assert restored is not None + model = rig.model + with mx.stream(rig.scheduler._stream): + warm = model(mx.array([remaining]), cache=restored) + cold = model(mx.array([PROMPT]), cache=model.make_cache()) + mx.eval(warm, cold) + assert mx.allclose(warm[:, -1], cold[:, -1], atol=1e-4) + finally: + rig.close() + + +def test_commit_is_skipped_under_memory_pressure( + tmp_path, mock_tokenizer, monkeypatch, split +): + rig = _Rig(tmp_path, mock_tokenizer, split=split, commit_blocks=1) + try: + scheduler = rig.scheduler + pressured = {"on": True} + monkeypatch.setattr( + scheduler, "_prefill_commit_blocked_by_pressure", lambda: pressured["on"] + ) + _, state = rig.start("r1", PROMPT) + rig.step(state, 2) + assert rig.table_tokens("r1") == 0 + + pressured["on"] = False + rig.step(state, 1) + # Everything completed so far is committed once pressure clears. + assert rig.table_tokens("r1") == 3 * BLOCK + finally: + rig.close() + + +@pytest.mark.parametrize( + "usage,limit,expected", [(500, 1000, False), (1000, 1000, True), (900, 0, False)] +) +def test_pressure_gate_follows_the_soft_limit( + tmp_path, mock_tokenizer, monkeypatch, usage, limit, expected +): + rig = _Rig(tmp_path, mock_tokenizer, split=False, commit_blocks=1) + try: + scheduler = rig.scheduler + scheduler._memory_limit_bytes = limit + monkeypatch.setattr(scheduler, "_current_usage_bytes", lambda **kw: usage) + assert scheduler._prefill_commit_blocked_by_pressure() is expected + finally: + rig.close() + + +def _packed(layer): + """Flat list of the arrays that make up a restored KV layer.""" + out = [] + + def walk(x): + if isinstance(x, mx.array): + out.append(x) + elif hasattr(x, "_fields"): + for name in x._fields: + walk(getattr(x, name)) + elif isinstance(x, (list, tuple)): + for item in x: + walk(item) + + walk(layer.state) + return out + + +def test_turboquant_blocks_committed_per_window_match_whole_prefix_conversion( + tmp_path, mock_tokenizer, split +): + from mlx_vlm.turboquant import TurboQuantKVCache + + import omlx.turboquant_kv # noqa: F401 (installs TurboQuantKVCache.from_cache) + + # One block per commit: the 8 stored tokens come from two separate windows. + rig = _Rig(tmp_path, mock_tokenizer, split=split, commit_blocks=1, tq_bits=4) + try: + _, state = rig.start("r1", PROMPT) + rig.step(state, 2) + assert rig.table_tokens("r1") == 2 * BLOCK + + table, _ = rig.probe(PROMPT) + restored = rig.prefix.reconstruct_cache(table) + assert restored is not None + assert type(restored[1]).__name__ == "TurboQuantKVCache" + + live = state.cache[1] # still fp16: conversion happens after prefill + assert type(live).__name__ == "KVCache" + whole = TurboQuantKVCache.from_cache(_window(live, 0, 2 * BLOCK), bits=4.0) + for got, want in zip(_packed(restored[1]), _packed(whole), strict=True): + assert mx.array_equal(got, want).item() + finally: + rig.close() + + +def _window(layer, start, end): + piece = type(layer)() + piece.keys = layer.keys[..., start:end, :] + piece.values = layer.values[..., start:end, :] + piece.offset = end - start + return piece + + +def test_window_longer_than_the_restored_prefix_is_stored_by_position( + tmp_path, mock_tokenizer, split +): + rig = _Rig(tmp_path, mock_tokenizer, split=split, commit_blocks=1) + try: + # Seed the cache with the first block, as an earlier request would. + _, state = rig.start("seed", PROMPT) + rig.step(state, 1) + assert rig.table_tokens("seed") == BLOCK + assert rig.scheduler._do_abort_request("seed") + + # The re-issue restores one block; its commit window (3 blocks) is + # then longer than the restored prefix (1 block). + rig.scheduler.config.prefill_progress_commit_blocks = 3 + request = Request( + request_id="again", + prompt=list(PROMPT), + sampling_params=SamplingParams(max_tokens=1), + ) + rig.scheduler.add_request(request) + rig.scheduler.waiting.clear() + rig.scheduler._prepare_prefix_cache_for_request(request) + assert request.cached_tokens == BLOCK + state = rig.scheduler._begin_prefill( + request, request.remaining_tokens[: len(PROMPT)], request.prompt_cache + ) + rig.step(state, 3) + assert rig.table_tokens("again") == 4 * BLOCK + assert rig.scheduler._do_abort_request("again") + + table, remaining = rig.probe(PROMPT) + assert table.num_tokens == 4 * BLOCK + restored = rig.prefix.reconstruct_cache(table) + model = rig.model + with mx.stream(rig.scheduler._stream): + warm = model(mx.array([remaining]), cache=restored) + cold = model(mx.array([PROMPT]), cache=model.make_cache()) + mx.eval(warm, cold) + assert mx.allclose(warm[:, -1], cold[:, -1], atol=1e-4) + finally: + rig.close() + + +def test_committed_boundary_markers_are_retired_once_stored( + tmp_path, mock_tokenizer, split +): + rig = _Rig(tmp_path, mock_tokenizer, split=split, commit_blocks=2) + try: + scheduler = rig.scheduler + _, state = rig.start("r1", PROMPT) + rig.step(state, 3) + scheduler._reap_prefill_commit("r1") + # Boundaries 4 and 8 were committed (a split-GDN commit moves their + # staged files); only the in-flight boundary 12 may remain. + assert sorted(scheduler._boundary_cache_snapshots["r1"]) == [3 * BLOCK] + finally: + rig.close() + + +def _finish(rig, request, state): + """Run prefill to the end, insert, decode one token and finalize.""" + from mlx_lm.generate import BatchGenerator + + scheduler = rig.scheduler + while not rig.step(state, 1): + pass + scheduler._emit_final_boundary_if_needed(state) + scheduler.batch_generator = BatchGenerator( + rig.model, + max_tokens=1, + sampler=lambda logits: mx.zeros(logits.shape[:-1], dtype=mx.int32), + stream=scheduler._stream, + ) + sampler, per_row = scheduler._build_sampler_and_processors(request.sampling_params) + state.sampler = sampler + state.sm = scheduler._build_state_machine(request) + state.per_row_lps = per_row + scheduler._insert_prefilled_request(request, state, []) + for _ in range(6): + _, responses = scheduler.batch_generator.next() + if responses: + break + _, finished = scheduler._process_batch_responses(responses) + scheduler._cleanup_finished(finished) + for future in list(scheduler._inflight_store_futures.values()): + future.result(timeout=20) + scheduler._drain_pending_async_removes() + rig.drain() + + +@pytest.mark.parametrize("commit_blocks", [0, 1, 2, 3]) +def test_completion_after_commits_stores_the_same_prefix_once( + tmp_path, mock_tokenizer, split, commit_blocks +): + rig = _Rig(tmp_path, mock_tokenizer, split=split, commit_blocks=commit_blocks) + try: + request, state = rig.start("r1", PROMPT) + _finish(rig, request, state) + + table, remaining = rig.probe(PROMPT) + assert table is not None and table.num_tokens == 4 * BLOCK + assert remaining == PROMPT[4 * BLOCK :] + assert len(table.block_ids) == len(set(table.block_ids)) == 4 + restored = rig.prefix.reconstruct_cache(table) + assert restored is not None + model = rig.model + with mx.stream(rig.scheduler._stream): + warm = model(mx.array([remaining]), cache=restored) + cold = model(mx.array([PROMPT]), cache=model.make_cache()) + mx.eval(warm, cold) + assert mx.allclose(warm[:, -1], cold[:, -1], atol=1e-4) + # No commit or snapshot bookkeeping outlives the request. + assert "r1" not in rig.scheduler._prefill_commits + assert "r1" not in rig.scheduler._boundary_cache_snapshots + finally: + rig.close() + + +def test_retry_after_prefill_oom_prefills_cold_even_with_committed_blocks( + tmp_path, mock_tokenizer +): + rig = _Rig(tmp_path, mock_tokenizer, split=False, commit_blocks=1) + try: + _, state = rig.start("r1", PROMPT) + rig.step(state, 2) + assert rig.scheduler._do_abort_request("r1") + + def lookup(request_id, retries): + request = Request( + request_id=request_id, + prompt=list(PROMPT), + sampling_params=SamplingParams(max_tokens=1), + ) + request.prefill_oom_retries = retries + rig.scheduler.add_request(request) + rig.scheduler._prepare_prefix_cache_for_request(request) + return request + + # A client re-issue resumes from the committed boundary... + assert lookup("reissue", 0).cached_tokens == 2 * BLOCK + # ...but the scheduler's own retry after a prefill memory failure + # stays cold (see _requeue_or_fail_prefill). + retry = lookup("retry", 1) + assert retry.cached_tokens == 0 + assert retry.remaining_tokens == PROMPT + finally: + rig.close() + + +def test_external_prefill_loop_commits_progress_too(tmp_path, mock_tokenizer, split): + rig = _Rig(tmp_path, mock_tokenizer, split=split, commit_blocks=2) + try: + scheduler = rig.scheduler + scheduler.config.chunked_prefill = False + request = Request( + request_id="ext", + prompt=list(PROMPT), + sampling_params=SamplingParams(max_tokens=1), + ) + scheduler.add_request(request) + scheduler.waiting.clear() + request.remaining_tokens = list(PROMPT) + scheduler.requests[request.request_id] = request + scheduler._do_external_prefill(request, list(PROMPT), None) + rig.drain() + assert rig.table_tokens("ext") == 4 * BLOCK + assert scheduler._do_abort_request("ext") + table, remaining = rig.probe(PROMPT) + assert table.num_tokens == 4 * BLOCK + assert remaining == PROMPT[4 * BLOCK :] + finally: + rig.close() + + +def test_dense_attention_model_commits_without_snapshots(tmp_path, mock_tokenizer): + from mlx_lm.models.llama import Model, ModelArgs + + mx.random.seed(5) + model = Model( + ModelArgs( + model_type="llama", + hidden_size=32, + num_hidden_layers=2, + intermediate_size=64, + num_attention_heads=2, + num_key_value_heads=1, + rms_norm_eps=1e-5, + vocab_size=32, + ) + ) + rig = _Rig(tmp_path, mock_tokenizer, split=False, commit_blocks=2) + try: + # Swap the hybrid model for a dense one under the same stores. + rig.model = rig.scheduler.model = model + rig.prefix.model = model + rig.ssd._expected_layer_cache_types = ["KVCache", "KVCache"] + _, state = rig.start("r1", PROMPT) + assert not state.boundary_enabled + rig.step(state, 3) + assert rig.table_tokens("r1") == 2 * BLOCK + assert rig.scheduler._do_abort_request("r1") + + table, remaining = rig.probe(PROMPT) + assert table.num_tokens == 2 * BLOCK + restored = rig.prefix.reconstruct_cache(table) + with mx.stream(rig.scheduler._stream): + warm = model(mx.array([remaining]), cache=restored) + cold = model(mx.array([PROMPT]), cache=model.make_cache()) + mx.eval(warm, cold) + assert mx.allclose(warm[:, -1], cold[:, -1], atol=1e-4) + finally: + rig.close() + + +def test_window_of_a_restored_turboquant_prefix_slices_the_packed_state( + tmp_path, mock_tokenizer +): + from mlx_lm.models.cache import KVCache + from mlx_vlm.turboquant import TurboQuantKVCache, _slice_state_range + + import omlx.turboquant_kv # noqa: F401 + + rig = _Rig(tmp_path, mock_tokenizer, split=False, commit_blocks=1) + try: + mx.random.seed(2) + k = mx.random.normal((1, 1, 12, 16)).astype(mx.float16) + fp16 = KVCache() + fp16.update_and_fetch(k, k) + packed = TurboQuantKVCache.from_cache(fp16, bits=4.0) + tail = KVCache() # the skipped last KV layer stays fp16 + tail.update_and_fetch(k, k) + + window = rig.scheduler._prefill_commit_window([packed, tail], 4, 12) + + assert window is not None + assert type(window[0]).__name__ == "TurboQuantKVCache" + assert window[0].offset == 8 + want = _slice_state_range(packed.keys, 4, 12) + assert mx.array_equal(window[0].keys.norms[:, :, :8], want.norms[:, :, :8]) + assert type(window[1]).__name__ == "KVCache" + assert window[1].offset == 8 + finally: + rig.close() + + +def test_window_refuses_composite_and_unknown_sliceable_layers( + tmp_path, mock_tokenizer +): + from mlx_lm.models.cache import CacheList, KVCache + + rig = _Rig(tmp_path, mock_tokenizer, split=False, commit_blocks=1) + try: + k = mx.zeros((1, 1, 8, 16), dtype=mx.float16) + kv = KVCache() + kv.update_and_fetch(k, k) + composite = CacheList(KVCache(), KVCache()) + assert rig.scheduler._prefill_commit_window([composite], 0, 8) is None + # A cache that has not reached the window end yet cannot be sliced. + assert rig.scheduler._prefill_commit_window([kv], 0, 12) is None + finally: + rig.close() From b30e72b6d0456d1602d0ff7c94d2fb3a4058c00f Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Thu, 1 Oct 2026 13:47:55 -0600 Subject: [PATCH 02/18] feat(settings): expose prefill_progress_commit_blocks 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. --- omlx/settings.py | 24 ++++++++++++++++++++++++ tests/test_settings.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/omlx/settings.py b/omlx/settings.py index c4590e04a5..7effced767 100644 --- a/omlx/settings.py +++ b/omlx/settings.py @@ -351,6 +351,10 @@ class SchedulerSettings: # any engine decodes, and each chunk accrues a decode time debt repaid # before the next chunk runs. Off restores the pre-fairness behavior. decode_fairness: bool = True + # Commit completed prefill blocks to the prefix cache every N blocks while a + # prompt is still prefilling, so an aborted or re-issued request resumes from + # the last committed block instead of token zero. 0 disables it. + prefill_progress_commit_blocks: int = 0 def to_dict(self) -> dict[str, Any]: """Convert to dictionary.""" @@ -371,12 +375,16 @@ def from_dict(cls, data: dict[str, Any]) -> SchedulerSettings: prefill_priority = data.get("prefill_priority", "context") if prefill_priority not in ("context", "speed"): prefill_priority = "context" + commit_blocks = data.get("prefill_progress_commit_blocks", 0) + if not isinstance(commit_blocks, int) or commit_blocks < 0: + commit_blocks = 0 return cls( max_concurrent_requests=value, embedding_batch_size=embedding_batch_size, chunked_prefill=bool(data.get("chunked_prefill", False)), prefill_priority=prefill_priority, decode_fairness=bool(data.get("decode_fairness", True)), + prefill_progress_commit_blocks=commit_blocks, ) @@ -1259,6 +1267,14 @@ def _apply_env_overrides(self) -> None: logger.warning( f"Invalid OMLX_EMBEDDING_BATCH_SIZE value: {embedding_batch_size}" ) + if commit_blocks := os.getenv("OMLX_PREFILL_PROGRESS_COMMIT_BLOCKS"): + try: + self.scheduler.prefill_progress_commit_blocks = int(commit_blocks) + except ValueError: + logger.warning( + f"Invalid OMLX_PREFILL_PROGRESS_COMMIT_BLOCKS value: " + f"{commit_blocks}" + ) # Cache settings if cache_enabled := os.getenv("OMLX_CACHE_ENABLED"): @@ -1770,6 +1786,11 @@ def validate(self) -> list[str]: f"Invalid embedding_batch_size: " f"{self.scheduler.embedding_batch_size} (must be > 0)" ) + if self.scheduler.prefill_progress_commit_blocks < 0: + errors.append( + f"Invalid prefill_progress_commit_blocks: " + f"{self.scheduler.prefill_progress_commit_blocks} (must be >= 0)" + ) # Cache validation if self.cache.gdn_ssd_split_enabled is True and self.cache.hot_cache_only: @@ -1945,6 +1966,9 @@ def to_scheduler_config(self) -> SchedulerConfig: chunked_prefill=self.scheduler.chunked_prefill, prefill_speed_priority=(self.scheduler.prefill_priority == "speed"), decode_fairness=self.scheduler.decode_fairness, + prefill_progress_commit_blocks=( + self.scheduler.prefill_progress_commit_blocks + ), initial_cache_blocks=self.cache.initial_cache_blocks, paged_ssd_cache_dir=str(ssd_dir) if ssd_dir else None, hot_cache_only=self.cache.hot_cache_only, diff --git a/tests/test_settings.py b/tests/test_settings.py index 416b71e9c6..1f3f6a5a8b 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -394,8 +394,40 @@ def test_to_dict(self): "chunked_prefill": False, "prefill_priority": "context", "decode_fairness": True, + "prefill_progress_commit_blocks": 0, } + def test_prefill_progress_commit_blocks_from_dict(self): + """Off by default; a positive count round-trips; junk falls back to off.""" + assert SchedulerSettings.from_dict({}).prefill_progress_commit_blocks == 0 + settings = SchedulerSettings.from_dict({"prefill_progress_commit_blocks": 4}) + assert settings.prefill_progress_commit_blocks == 4 + for bad in ("many", None, -3): + assert ( + SchedulerSettings.from_dict( + {"prefill_progress_commit_blocks": bad} + ).prefill_progress_commit_blocks + == 0 + ) + + def test_prefill_progress_commit_blocks_reaches_scheduler_config(self, tmp_path): + settings = GlobalSettings(base_path=tmp_path) + assert settings.to_scheduler_config().prefill_progress_commit_blocks == 0 + settings.scheduler.prefill_progress_commit_blocks = 3 + assert settings.to_scheduler_config().prefill_progress_commit_blocks == 3 + + def test_prefill_progress_commit_blocks_env_override(self, tmp_path): + with patch.dict( + os.environ, {"OMLX_PREFILL_PROGRESS_COMMIT_BLOCKS": "2"}, clear=False + ): + settings = GlobalSettings.load(base_path=tmp_path) + assert settings.scheduler.prefill_progress_commit_blocks == 2 + + def test_prefill_progress_commit_blocks_must_not_be_negative(self, tmp_path): + settings = GlobalSettings(base_path=tmp_path) + settings.scheduler.prefill_progress_commit_blocks = -1 + assert any("prefill_progress_commit_blocks" in e for e in settings.validate()) + def test_decode_fairness_from_dict(self): """Defaults on; explicit false round-trips.""" assert SchedulerSettings.from_dict({}).decode_fairness is True From bf1611b5291b030250ef3b5d37128a3c4882b6e0 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Thu, 1 Oct 2026 14:55:13 -0600 Subject: [PATCH 03/18] fix(settings): reject bool for prefill_progress_commit_blocks --- omlx/settings.py | 7 ++++++- tests/test_settings.py | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/omlx/settings.py b/omlx/settings.py index 7effced767..d363d0f111 100644 --- a/omlx/settings.py +++ b/omlx/settings.py @@ -376,7 +376,12 @@ def from_dict(cls, data: dict[str, Any]) -> SchedulerSettings: if prefill_priority not in ("context", "speed"): prefill_priority = "context" commit_blocks = data.get("prefill_progress_commit_blocks", 0) - if not isinstance(commit_blocks, int) or commit_blocks < 0: + # bool is an int subclass: True must not silently become 1 block. + if ( + not isinstance(commit_blocks, int) + or isinstance(commit_blocks, bool) + or commit_blocks < 0 + ): commit_blocks = 0 return cls( max_concurrent_requests=value, diff --git a/tests/test_settings.py b/tests/test_settings.py index 1f3f6a5a8b..b4218c8366 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -402,7 +402,7 @@ def test_prefill_progress_commit_blocks_from_dict(self): assert SchedulerSettings.from_dict({}).prefill_progress_commit_blocks == 0 settings = SchedulerSettings.from_dict({"prefill_progress_commit_blocks": 4}) assert settings.prefill_progress_commit_blocks == 4 - for bad in ("many", None, -3): + for bad in ("many", None, -3, True, False): assert ( SchedulerSettings.from_dict( {"prefill_progress_commit_blocks": bad} From 797f7e4f00f9f59342a70c07ec89b94dd9072563 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Thu, 1 Oct 2026 14:55:13 -0600 Subject: [PATCH 04/18] fix(scheduler): defer prefill commit teardown instead of blocking the 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. --- omlx/scheduler.py | 376 ++++++++++++----- .../test_scheduler_prefill_progress_commit.py | 377 +++++++++++++++++- 2 files changed, 652 insertions(+), 101 deletions(-) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 6502d54dd9..83c100fa1b 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -1335,6 +1335,14 @@ def _is_turboquant_kv_family_cache(cache_obj: Any) -> bool: ) or _is_turboquant_kv_cache(cache_obj) +# Bounded wait for in-flight prefill commits at shutdown only; the hot path +# never waits (see Scheduler._after_commit). +PREFILL_COMMIT_SHUTDOWN_WAIT_S = 30.0 +# A teardown deferred behind a commit that has not finished after this long +# is logged once; it stays pending and is dropped at shutdown. +PREFILL_COMMIT_STUCK_LOG_S = 60.0 + + def _prefill_commit_blocks(config: Any) -> int: """``prefill_progress_commit_blocks`` of a config, 0 when unset or invalid.""" value = getattr(config, "prefill_progress_commit_blocks", 0) @@ -2223,6 +2231,17 @@ def __init__( # request_id -> (future, committed token count) of the in-flight # incremental prefill commit (see _commit_prefill_progress). self._prefill_commits: dict[str, tuple[concurrent.futures.Future, int]] = {} + # Own single-thread executor so commits never queue behind the + # post-finish final stores (28GB+ memcpys) on _store_cache_executor. + self._prefill_commit_executor: concurrent.futures.ThreadPoolExecutor | None = ( + None + ) + # request_id -> destructive teardown steps (release block table, + # retire snapshots, ...) postponed until that request's in-flight + # commit has finished. Touched on the scheduler thread only. + self._deferred_teardowns: dict[str, list[Callable[[], None]]] = {} + self._deferred_teardown_since: dict[str, float] = {} + self._stuck_teardown_logged: set[str] = set() self.requests: dict[str, Request] = {} # All requests by ID self.finished_req_ids: set[str] = set() # Recently finished self._generation_overflow_recovery_ids: set[str] = set() @@ -2533,6 +2552,7 @@ def __init__( max_workers=1, thread_name_prefix="omlx-store-cache", ) + self._ensure_prefill_commit_executor() # Gate caps the post-completion store-cache pipeline so a burst # of finishes cannot pile up unbounded KV caches in memory while # the single writer drains. Cap starts at max_concurrent_requests @@ -2774,9 +2794,14 @@ def _async_store_cache_worker( extra_key_ranges: list[tuple[int, tuple[Any, ...]]] | None, hot_cache_write_back: bool = True, incremental_commit: bool = False, + after_commit: concurrent.futures.Future | None = None, ) -> None: """Run store_cache + paged_cache cleanup off the inference thread. + ``after_commit`` is the request's in-flight incremental commit: the + store waits for it here, on this worker, so the two never race on the + block table and the inference thread never waits. + ``incremental_commit`` marks a mid-prefill commit: ``cache_to_store`` holds only the tokens after the request's existing block table, and the table stays alive so the next commit (or the final store) extends @@ -2814,6 +2839,8 @@ def _async_store_cache_worker( threading.RLock so concurrent access from main and worker is safe. """ self._store_cache_thread_id = threading.get_ident() + if after_commit is not None: + concurrent.futures.wait([after_commit]) window_kwargs = {"cache_covers_suffix_only": True} if incremental_commit else {} try: # Hold _mx_buffer_access_lock across the worker's mx-buffer @@ -7712,13 +7739,34 @@ def _prefill_commit_window( self._apply_turboquant_kv_convert(window) return window + def _ensure_prefill_commit_executor( + self, + ) -> concurrent.futures.ThreadPoolExecutor: + executor = self._prefill_commit_executor + if executor is None: + executor = concurrent.futures.ThreadPoolExecutor( + max_workers=1, thread_name_prefix="omlx-prefill-commit" + ) + self._prefill_commit_executor = executor + return executor + + def _retire_committed_markers(self, request_id: str, committed_tokens: int) -> None: + """Drop snapshot markers a commit covering ``committed_tokens`` consumed. + + The commit worker moves (split-GDN) or reads (inline) the staged + snapshot of every committed boundary, so their markers must not reach + the final store, which would try to load a moved file. + """ + snapshots = self._boundary_cache_snapshots.get(request_id) + if snapshots: + for token_count in [tc for tc in snapshots if tc <= committed_tokens]: + del snapshots[token_count] + def _reap_prefill_commit(self, request_id: str) -> None: """Retire a finished commit: drop snapshot markers it consumed. - Runs on the inference thread. The commit worker moves (split-GDN) or - reads (inline) the staged snapshot of every committed boundary, so - their markers must not reach the final store, which would try to load - a moved file. A failed commit leaves them in place for the next try. + Runs on the inference thread and never waits. A failed commit leaves + its markers in place for the next try. """ pending = (getattr(self, "_prefill_commits", None) or {}).get(request_id) if pending is None: @@ -7729,31 +7777,91 @@ def _reap_prefill_commit(self, request_id: str) -> None: del self._prefill_commits[request_id] try: ok = bool(future.result()) - except Exception: + except Exception as e: + logger.warning("Prefill commit for %s failed: %s", request_id, e) ok = False - if not ok: - return - snapshots = self._boundary_cache_snapshots.get(request_id) - if snapshots: - for token_count in [tc for tc in snapshots if tc <= committed_tokens]: - del snapshots[token_count] + if ok: + self._retire_committed_markers(request_id, committed_tokens) + + def _inflight_commit_future( + self, request_id: str + ) -> concurrent.futures.Future | None: + """The request's commit future while it is still running, else None.""" + self._reap_prefill_commit(request_id) + pending = (getattr(self, "_prefill_commits", None) or {}).get(request_id) + return pending[0] if pending is not None else None - def _settle_prefill_commits(self, request_id: str) -> None: - """Wait for an in-flight commit before its request is torn down. + def _after_commit(self, request_id: str, teardown: Callable[[], None]) -> bool: + """Run a destructive teardown step once the request's commit is done. Teardown releases the block table and removes the snapshot directory, - which the commit worker is still reading. Commits are a few blocks, so - the wait is short; the blocks it stores stay in the prefix cache. - """ - pending = (getattr(self, "_prefill_commits", None) or {}).get(request_id) - if pending is None: - return + which the commit worker may still be reading or moving. Never waits: + with no commit in flight the step runs now; otherwise it is queued and + runs from ``_process_finished_commits`` on the scheduler thread, after + the commit finished (successfully or not). Returns True when deferred. + """ + if self._inflight_commit_future(request_id) is None: + self._run_deferred_teardowns(request_id) # keep submission order + self._run_teardown_step(request_id, teardown) + return False + self._deferred_teardowns.setdefault(request_id, []).append(teardown) + self._deferred_teardown_since.setdefault(request_id, time.monotonic()) + logger.debug( + "Deferring teardown of %s until its prefill commit ends", request_id + ) + return True + + def _teardown_pending(self, request_id: str) -> bool: + """True while a deferred teardown of this request id has not run.""" + return request_id in self._deferred_teardowns + + def _run_teardown_step(self, request_id: str, teardown: Callable[[], None]) -> None: try: - pending[0].result(timeout=60) + teardown() except Exception as e: - logger.warning("Prefill commit for %s did not settle: %s", request_id, e) - self._reap_prefill_commit(request_id) - self._prefill_commits.pop(request_id, None) + logger.warning("Teardown step for %s failed: %s", request_id, e) + + def _run_deferred_teardowns(self, request_id: str) -> None: + steps = self._deferred_teardowns.pop(request_id, None) + self._deferred_teardown_since.pop(request_id, None) + self._stuck_teardown_logged.discard(request_id) + for teardown in steps or (): + self._run_teardown_step(request_id, teardown) + + def _process_finished_commits(self) -> None: + """Retire finished commits and run the teardowns waiting on them. + + Called at the start of every step on the scheduler thread; only reads + future state, so commit workers never touch scheduler state. + """ + for request_id in list(self._prefill_commits): + self._reap_prefill_commit(request_id) + if request_id not in self._prefill_commits: + self._run_deferred_teardowns(request_id) + now = time.monotonic() + for request_id, since in self._deferred_teardown_since.items(): + if ( + now - since >= PREFILL_COMMIT_STUCK_LOG_S + and request_id not in self._stuck_teardown_logged + ): + self._stuck_teardown_logged.add(request_id) + logger.warning( + "Teardown of %s still waits for its prefill commit after %.0fs", + request_id, + now - since, + ) + + def _wait_for_prefill_commits(self, timeout: float) -> int: + """Block until every commit ends or ``timeout``; returns the stragglers. + + Reset and shutdown only: the hot path never waits on a commit. + """ + futures = [future for future, _ in self._prefill_commits.values()] + not_done: set = set() + if futures: + _done, not_done = concurrent.futures.wait(futures, timeout=timeout) + self._process_finished_commits() + return len(not_done) def _commit_prefill_progress( self, request: "Request", prompt_cache: list[Any], total_tokens: int @@ -7854,7 +7962,7 @@ def _commit_prefill_progress_unchecked( # streams are thread-local; see _async_store_cache_worker). mx.eval(*arrays) - future = self._store_cache_executor.submit( + future = self._ensure_prefill_commit_executor().submit( self._commit_prefill_worker, rid, tokens, @@ -11734,9 +11842,6 @@ def _do_abort_request(self, request_id: str) -> bool: return False self._clear_request_admission_bookkeeping(request_id) - # Committed prefill blocks stay in the prefix cache; let an in-flight - # commit finish before the table and snapshots are released below. - self._settle_prefill_commits(request_id) # Remove from waiting queue if request.status == RequestStatus.WAITING: @@ -11783,24 +11888,32 @@ def _do_abort_request(self, request_id: str) -> bool: # forever (#766). self._cleanup_specprefill(request_id) - # Release blocks for eviction (same as _cleanup_finished) - if self.paged_cache_manager is not None: - block_table = self.paged_cache_manager.get_block_table(request_id) - if block_table is None and hasattr(request, "block_table"): - block_table = request.block_table - if block_table: - released = self.paged_cache_manager.release_for_eviction( - block_table.block_ids - ) - if released > 0: - logger.debug( - f"Released {released} blocks for eviction on abort " - f"(request {request_id})" + # Release blocks for eviction (same as _cleanup_finished) and drop the + # request's block-aware entry, boundary snapshots (RAM and SSD). Blocks + # an incremental prefill commit stored stay in the prefix cache; if a + # commit is still running, these steps wait for it (without blocking + # this thread) because the worker is using the table and snapshots. + def release_cache_state() -> None: + if self.paged_cache_manager is not None: + block_table = self.paged_cache_manager.get_block_table(request_id) + if block_table is None and hasattr(request, "block_table"): + block_table = request.block_table + if block_table: + released = self.paged_cache_manager.release_for_eviction( + block_table.block_ids ) + if released > 0: + logger.debug( + f"Released {released} blocks for eviction on abort " + f"(request {request_id})" + ) + if self.block_aware_cache is not None: + self.block_aware_cache.clear_request_entry(request_id) + self._boundary_cache_snapshots.pop(request_id, None) + if self._boundary_snapshot_store is not None: + self._boundary_snapshot_store.cleanup_request(request_id) - # Clear request entry from block_aware_cache - if self.block_aware_cache is not None: - self.block_aware_cache.clear_request_entry(request_id) + self._after_commit(request_id, release_cache_state) # Clean up streaming detokenizer to prevent state contamination self._cleanup_detokenizer(request_id) @@ -11814,11 +11927,6 @@ def _do_abort_request(self, request_id: str) -> bool: if hasattr(self.model, "clear_pending_embeddings"): self.model.clear_pending_embeddings() - # Drop any boundary snapshot for this request. - self._boundary_cache_snapshots.pop(request_id, None) - if self._boundary_snapshot_store is not None: - self._boundary_snapshot_store.cleanup_request(request_id) - # Remove from prefill progress tracker. get_prefill_tracker().remove(request_id) @@ -11861,6 +11969,7 @@ def has_requests(self) -> bool: or self.prefilling or self.running or self._pending_async_removes + or self._deferred_teardowns or self._deferred_clear_at is not None or self._pending_reclaim_request or self._pending_pressure_clear @@ -11915,6 +12024,11 @@ def _effective_max_num_seqs(self) -> int: return 1 return max(1, self.config.max_num_seqs) + def _drop_snapshots_now(self, request_id: str) -> None: + self._boundary_cache_snapshots.pop(request_id, None) + if self._boundary_snapshot_store is not None: + self._boundary_snapshot_store.cleanup_request(request_id) + def _drop_boundary_snapshots_for_request(self, request_id: str) -> None: """Release a failed request's boundary snapshots (RAM and SSD). @@ -11924,17 +12038,20 @@ def _drop_boundary_snapshots_for_request(self, request_id: str) -> None: must do the same or every failure strands a snapshot set until process exit (#3226). """ - self._settle_prefill_commits(request_id) - self._boundary_cache_snapshots.pop(request_id, None) - if self._boundary_snapshot_store is not None: - try: - self._boundary_snapshot_store.cleanup_request(request_id) - except Exception as e: - logger.debug( - "Boundary snapshot store cleanup failed for %s: %s", - request_id, - e, - ) + + def drop() -> None: + self._boundary_cache_snapshots.pop(request_id, None) + if self._boundary_snapshot_store is not None: + try: + self._boundary_snapshot_store.cleanup_request(request_id) + except Exception as e: + logger.debug( + "Boundary snapshot store cleanup failed for %s: %s", + request_id, + e, + ) + + self._after_commit(request_id, drop) def fail_all_requests(self) -> list[str]: """Remove all running and waiting requests after unrecoverable error. @@ -12653,6 +12770,11 @@ def _schedule_waiting( self._clear_store_cache_admission_blocker(request.request_id) if self._should_defer_for_cache_freshness(request): break + if self._teardown_pending(request.request_id): + # A previous run of this id is still being torn down behind + # its prefill commit; the head waits (no blocking) so the + # deferred cleanup cannot hit the new run's state. + break request = self.waiting.popleft() self._cache_freshness_waits.pop(request.request_id, None) @@ -13706,11 +13828,16 @@ def _release_paged_cache_for_request(self, request_id: str) -> None: very memory pressure that triggered the rejection) and orphan ``_request_tables`` entries. """ - self._settle_prefill_commits(request_id) - if self.block_aware_cache is not None: - self.block_aware_cache.release_cache(request_id) - elif self.paged_cache_manager is not None: - self.paged_cache_manager.delete_block_table(request_id) + + def release_table() -> None: + if self.block_aware_cache is not None: + self.block_aware_cache.release_cache(request_id) + elif self.paged_cache_manager is not None: + self.paged_cache_manager.delete_block_table(request_id) + + # An in-flight prefill commit is still using the table: wait for it + # without blocking this thread. + self._after_commit(request_id, release_table) # SpecPrefill primes an independent ``_draft_prefix_cache`` in # ``_try_specprefill_scoring`` whose block refs are tracked @@ -13729,6 +13856,19 @@ def _release_paged_cache_for_request(self, request_id: str) -> None: exc_info=True, ) + def _release_finished_table( + self, request_id: str, request: "Request | None" = None + ) -> None: + """Release a finished request's blocks for eviction; drop its entry.""" + block_table = None + if self.paged_cache_manager: + block_table = self.paged_cache_manager.get_block_table(request_id) + if block_table is None and request is not None: + block_table = getattr(request, "block_table", None) + if block_table and self.paged_cache_manager: + self.paged_cache_manager.release_for_eviction(block_table.block_ids) + self.block_aware_cache.clear_request_entry(request_id) + def _cleanup_finished(self, finished_ids: set[str]) -> None: """Clean up finished requests and store caches for reuse.""" # Synchronize pending engine stream operations before cache storage. @@ -13757,9 +13897,16 @@ def _cleanup_finished(self, finished_ids: set[str]) -> None: if finished_drafter is not None: finished_drafter.release_request(request_id) request = self.running.get(request_id) - # A mid-prefill commit still in flight must land (and retire its - # consumed snapshot markers) before the final store reads them. - self._settle_prefill_commits(request_id) + # A mid-prefill commit still in flight consumes its snapshot + # markers and extends the block table. Retire those markers from + # the final store's view now (assuming success: a failed commit + # only costs the cached tail), and chain the store after the + # commit on its worker so the two never race on the table. + commit_future = self._inflight_commit_future(request_id) + if commit_future is not None: + self._retire_committed_markers( + request_id, self._prefill_commits[request_id][1] + ) # Store cache for future reuse (G2-async): submit to background # executor so the post-finish 28GB+ memcpy doesn't block response @@ -13986,6 +14133,7 @@ def _cleanup_finished(self, finished_ids: set[str]) -> None: request.vlm_extra_key_token_start_for_cache, request.vlm_extra_key_ranges_for_cache, hot_cache_write_back, + after_commit=commit_future, ) except BaseException: if gate is not None: @@ -14076,34 +14224,24 @@ def _cleanup_finished(self, finished_ids: set[str]) -> None: block_size, available_boundaries, ) - block_table = None - if self.paged_cache_manager: - block_table = self.paged_cache_manager.get_block_table( - request_id - ) - if block_table and self.paged_cache_manager: - self.paged_cache_manager.release_for_eviction( - block_table.block_ids - ) - self.block_aware_cache.clear_request_entry(request_id) + self._after_commit( + request_id, + lambda rid=request_id: self._release_finished_table( + rid + ), + ) except Exception as e: logger.debug( f"Failed to submit async store for {request_id}: {e}" ) else: # No extracted_cache to store, but ensure block leak guard. - block_table = None - if self.paged_cache_manager: - block_table = self.paged_cache_manager.get_block_table( - request_id - ) - if block_table is None and hasattr(request, "block_table"): - block_table = request.block_table - if block_table and self.paged_cache_manager: - self.paged_cache_manager.release_for_eviction( - block_table.block_ids - ) - self.block_aware_cache.clear_request_entry(request_id) + self._after_commit( + request_id, + lambda rid=request_id, req=request: ( + self._release_finished_table(rid, req) + ), + ) # Remove from running if request_id in self.running: @@ -14157,7 +14295,12 @@ def _cleanup_finished(self, finished_ids: set[str]) -> None: # an async store_future is in flight, defer cleanup until the # worker finishes (handled in _drain_pending_async_removes). if self._boundary_snapshot_store is not None and store_future is None: - self._boundary_snapshot_store.cleanup_request(request_id) + self._after_commit( + request_id, + lambda rid=request_id: self._boundary_snapshot_store.cleanup_request( + rid + ), + ) # Track as finished self.finished_req_ids.add(request_id) @@ -14486,10 +14629,10 @@ def collect(request: Request | None) -> None: for request in retry_candidates: request.generation_overflow_retries += 1 request_id = request.request_id - self._settle_prefill_commits(request_id) - self._boundary_cache_snapshots.pop(request_id, None) - if self._boundary_snapshot_store is not None: - self._boundary_snapshot_store.cleanup_request(request_id) + self._after_commit( + request_id, + lambda rid=request_id: self._drop_snapshots_now(rid), + ) get_prefill_tracker().remove(request_id) if request.generation_overflow_retries > max_generation_overflow_retries: failed_ids.append(request_id) @@ -14654,6 +14797,10 @@ def step(self) -> SchedulerOutput: self._decode_activity_key, len(self.running) ) + # Retire finished prefill commits and run the teardowns that waited + # for them (never blocks: only reads future state). + self._process_finished_commits() + # Process pending aborts FIRST (thread-safe with hybrid executor) self._process_pending_aborts() @@ -14994,6 +15141,12 @@ def reset(self) -> None: # use the same bounded teardown barrier as shutdown() before aborting # requests or clearing caches. The drain performs the request-local # cleanup only after every future has completed. + if self._wait_for_prefill_commits(FATAL_TEARDOWN_TIMEOUT_S): + fatal_exit( + "Scheduler reset timed out after " + f"{FATAL_TEARDOWN_TIMEOUT_S:.0f}s waiting for prefill commit(s)" + ) + return inflight = list(self._inflight_store_futures.values()) if inflight: logger.info( @@ -15035,6 +15188,10 @@ def reset(self) -> None: self._pending_async_removes.clear() self._inflight_store_futures.clear() self._inflight_store_info.clear() + self._deferred_teardowns.clear() + self._deferred_teardown_since.clear() + self._stuck_teardown_logged.clear() + self._prefill_commits.clear() self._cache_freshness_waits.clear() self._prefix_cache_prepared.clear() self.batch_generator = None @@ -15115,6 +15272,36 @@ def deep_reset(self) -> None: logger.info("Deep reset completed - all caches cleared") + def _shutdown_prefill_commits(self) -> None: + """Finish or safely abandon prefill commits and their teardowns. + + The bounded wait is acceptable here only. A commit that outlives it + is abandoned: its pending teardowns are dropped (the snapshot + directories are removed by ``cleanup_all`` and the process is going + away), and its executor is not joined. + """ + executor = self._prefill_commit_executor + stragglers = self._wait_for_prefill_commits(PREFILL_COMMIT_SHUTDOWN_WAIT_S) + if stragglers: + logger.warning( + "Abandoning %d prefill commit(s) still running at shutdown " + "(%d pending teardown(s) dropped)", + stragglers, + len(self._deferred_teardowns), + ) + elif executor is not None: + try: + executor.submit(clear_thread_streams).result(timeout=10) + except Exception as e: + logger.warning("Prefill commit worker stream cleanup failed: %s", e) + self._deferred_teardowns.clear() + self._deferred_teardown_since.clear() + self._stuck_teardown_logged.clear() + self._prefill_commits.clear() + if executor is not None: + executor.shutdown(wait=False) + self._prefill_commit_executor = None + def _store_persistence_progress(self): manager = self.paged_ssd_cache_manager thread_id = getattr(self, "_store_cache_thread_id", None) @@ -15137,6 +15324,7 @@ def shutdown(self) -> None: # The store-cache gate is a non-blocking counter (#1496), so there is # no step-thread caller to wake here. Inflight futures are drained # below before the executor is asked to shut down. + self._shutdown_prefill_commits() # Wait for any inflight async store_cache futures + drain pending # batch_generator removes so the writer thread / underlying paged SSD # cache see all blocks before close(). diff --git a/tests/test_scheduler_prefill_progress_commit.py b/tests/test_scheduler_prefill_progress_commit.py index 6d2ba72f47..8706a50750 100644 --- a/tests/test_scheduler_prefill_progress_commit.py +++ b/tests/test_scheduler_prefill_progress_commit.py @@ -8,6 +8,8 @@ """ import concurrent.futures +import threading +import time import mlx.core as mx import pytest @@ -116,8 +118,13 @@ def step(self, state, chunks): return done def drain(self): - """Wait for every in-flight store or commit on the store executor.""" - self.scheduler._store_cache_executor.submit(lambda: None).result(timeout=20) + """Wait for every in-flight store or commit, then retire the commits.""" + s = self.scheduler + s._store_cache_executor.submit(lambda: None).result(timeout=20) + commit_executor = getattr(s, "_prefill_commit_executor", None) + if commit_executor is not None: + commit_executor.submit(lambda: None).result(timeout=20) + s._process_finished_commits() def close(self): self.scheduler.shutdown() @@ -345,13 +352,11 @@ def test_committed_boundary_markers_are_retired_once_stored( rig.close() -def _finish(rig, request, state): - """Run prefill to the end, insert, decode one token and finalize.""" +def _decode_to_finish(rig, request, state): + """Insert a fully prefilled request, decode one token, return finished ids.""" from mlx_lm.generate import BatchGenerator scheduler = rig.scheduler - while not rig.step(state, 1): - pass scheduler._emit_final_boundary_if_needed(state) scheduler.batch_generator = BatchGenerator( rig.model, @@ -369,7 +374,15 @@ def _finish(rig, request, state): if responses: break _, finished = scheduler._process_batch_responses(responses) - scheduler._cleanup_finished(finished) + return finished + + +def _finish(rig, request, state): + """Run prefill to the end, insert, decode one token and finalize.""" + scheduler = rig.scheduler + while not rig.step(state, 1): + pass + scheduler._cleanup_finished(_decode_to_finish(rig, request, state)) for future in list(scheduler._inflight_store_futures.values()): future.result(timeout=20) scheduler._drain_pending_async_removes() @@ -547,3 +560,353 @@ def test_window_refuses_composite_and_unknown_sliceable_layers( assert rig.scheduler._prefill_commit_window([kv], 0, 12) is None finally: rig.close() + + +# --- Teardown while a commit is in flight -------------------------------------- + + +class _CommitGate: + """Holds the commit worker on an Event so a test controls its lifetime.""" + + def __init__(self, scheduler, monkeypatch, fail=False): + self.release = threading.Event() + self.entered = threading.Event() + real = scheduler._commit_prefill_worker + + def gated(*args, **kwargs): + self.entered.set() + assert self.release.wait(30) + if fail: + raise RuntimeError("commit exploded") + return real(*args, **kwargs) + + monkeypatch.setattr(scheduler, "_commit_prefill_worker", gated) + + +@pytest.fixture +def gated(monkeypatch): + """Factory: rig with a controllable commit worker; released on teardown.""" + gates = [] + + def make(rig, fail=False): + gate = _CommitGate(rig.scheduler, monkeypatch, fail=fail) + gates.append(gate) + return gate + + yield make + for gate in gates: + gate.release.set() + + +def _returns_promptly(fn, *args, timeout=5.0): + """Run ``fn`` on a helper thread; fail if it blocks past ``timeout``.""" + box = {} + + def run(): + box["value"] = fn(*args) + + thread = threading.Thread(target=run, daemon=True) + thread.start() + thread.join(timeout) + assert not thread.is_alive(), f"{fn.__name__} blocked on the in-flight commit" + return box.get("value") + + +def _inflight_commit(rig, gate, split_chunks=2): + """Prefill until the first commit is submitted and held by the gate.""" + _, state = rig.start("r1", PROMPT) + for _ in range(split_chunks): + rig.scheduler._step_prefill_chunk(state) + assert gate.entered.wait(20) + future, _ = rig.scheduler._prefill_commits["r1"] + assert not future.done() + return state + + +def _await_teardown(rig, gate): + gate.release.set() + rig.drain() + assert not rig.scheduler._deferred_teardowns + + +def test_abort_with_a_commit_in_flight_defers_cleanup_until_it_completes( + tmp_path, mock_tokenizer, gated, split +): + rig = _Rig(tmp_path, mock_tokenizer, split=split, commit_blocks=2) + gate = gated(rig) + try: + scheduler = rig.scheduler + _inflight_commit(rig, gate) + cleanups = [] + real_cleanup = rig.boundary.cleanup_request + rig.boundary.cleanup_request = lambda rid: ( + cleanups.append(rid), + real_cleanup(rid), + ) + + assert _returns_promptly(scheduler._do_abort_request, "r1") + # The request is gone from the scheduler, but the snapshots and the + # block table the worker is using are untouched while it runs. + assert "r1" not in scheduler.requests + assert scheduler._boundary_cache_snapshots.get("r1") + assert cleanups == [] + assert scheduler.has_requests() + + _await_teardown(rig, gate) + assert cleanups == ["r1"] + assert "r1" not in scheduler._boundary_cache_snapshots + assert "r1" not in rig.prefix._request_tables + assert not scheduler._deferred_teardowns + + table, remaining = rig.probe(PROMPT) + assert table is not None and table.num_tokens == 2 * BLOCK + assert remaining == PROMPT[2 * BLOCK :] + restored = rig.prefix.reconstruct_cache(table) + assert restored is not None + model = rig.model + with mx.stream(scheduler._stream): + warm = model(mx.array([remaining]), cache=restored) + cold = model(mx.array([PROMPT]), cache=model.make_cache()) + mx.eval(warm, cold) + assert mx.allclose(warm[:, -1], cold[:, -1], atol=1e-4) + finally: + gate.release.set() + rig.close() + + +def test_prefill_failure_with_a_commit_in_flight_defers_cleanup( + tmp_path, mock_tokenizer, gated, split +): + rig = _Rig(tmp_path, mock_tokenizer, split=split, commit_blocks=2) + gate = gated(rig) + try: + scheduler = rig.scheduler + _inflight_commit(rig, gate) + + _returns_promptly(scheduler._drop_boundary_snapshots_for_request, "r1") + _returns_promptly(scheduler._release_paged_cache_for_request, "r1") + assert scheduler._boundary_cache_snapshots.get("r1") + assert scheduler.has_requests() + + _await_teardown(rig, gate) + assert "r1" not in scheduler._boundary_cache_snapshots + # The rejection path frees the table (release_cache), as before. + assert rig.paged.get_block_table("r1") is None + assert "r1" not in rig.prefix._request_tables + finally: + gate.release.set() + rig.close() + + +def test_overflow_retry_defers_snapshot_cleanup_and_holds_readmission( + tmp_path, mock_tokenizer, gated +): + rig = _Rig(tmp_path, mock_tokenizer, split=True, commit_blocks=2) + gate = gated(rig) + try: + scheduler = rig.scheduler + request, state = rig.start("r1", PROMPT) + for _ in range(2): + scheduler._step_prefill_chunk(state) + assert gate.entered.wait(20) + + _returns_promptly(scheduler._drop_boundary_snapshots_for_request, "r1") + scheduler.waiting.append(request) + scheduled, _ = scheduler._schedule_waiting() + # Same request id: the head of the queue waits for its own teardown. + assert scheduled == [] + assert list(scheduler.waiting) == [request] + + _await_teardown(rig, gate) + assert not scheduler._teardown_pending("r1") + finally: + gate.release.set() + rig.close() + + +def test_finish_with_a_commit_in_flight_chains_the_final_store_after_it( + tmp_path, mock_tokenizer, monkeypatch, gated, split +): + rig = _Rig(tmp_path, mock_tokenizer, split=split, commit_blocks=2) + gate = gated(rig) + try: + scheduler = rig.scheduler + request, state = rig.start("r1", PROMPT) + while not scheduler._step_prefill_chunk(state): + pass + assert gate.entered.wait(20) + events = [] + real_store = rig.prefix.store_cache + + def traced(*args, **kwargs): + kind = "commit" if kwargs.get("cache_covers_suffix_only") else "final" + events.append(f"{kind}-start") + try: + return real_store(*args, **kwargs) + finally: + events.append(f"{kind}-end") + + monkeypatch.setattr(rig.prefix, "store_cache", traced) + finished = _decode_to_finish(rig, request, state) + + # MLX streams are thread-local, so this runs on the test thread; the + # watchdog frees a regressed implementation that would block instead. + watchdog = threading.Timer(8.0, gate.release.set) + watchdog.start() + started = time.monotonic() + scheduler._cleanup_finished(finished) + elapsed = time.monotonic() - started + watchdog.cancel() + assert elapsed < 4.0, "_cleanup_finished blocked on the in-flight commit" + future = scheduler._inflight_store_futures["r1"] + time.sleep(0.3) + assert not future.done() # waiting for the commit, not racing it + assert events == [] # the final store has not touched the table yet + + gate.release.set() + future.result(timeout=20) + scheduler._drain_pending_async_removes() + rig.drain() + + # Strictly sequential: the commit ends before the final store starts. + assert events == ["commit-start", "commit-end", "final-start", "final-end"] + table, remaining = rig.probe(PROMPT) + assert table is not None and table.num_tokens == 4 * BLOCK + assert len(table.block_ids) == len(set(table.block_ids)) == 4 + assert rig.prefix.reconstruct_cache(table) is not None + assert not scheduler._deferred_teardowns + assert "r1" not in scheduler._prefill_commits + finally: + gate.release.set() + rig.close() + + +def test_commit_that_raises_still_runs_the_teardown_and_leaves_no_blocks( + tmp_path, mock_tokenizer, gated, split +): + rig = _Rig(tmp_path, mock_tokenizer, split=split, commit_blocks=2) + gate = gated(rig, fail=True) + try: + scheduler = rig.scheduler + _inflight_commit(rig, gate) + _returns_promptly(scheduler._do_abort_request, "r1") + + gate.release.set() + rig.drain() + assert not scheduler._deferred_teardowns + assert "r1" not in scheduler._prefill_commits + assert "r1" not in scheduler._boundary_cache_snapshots + assert rig.paged.get_block_table("r1") is None + table, remaining = rig.probe(PROMPT) + assert table is None + assert remaining == PROMPT + finally: + gate.release.set() + rig.close() + + +def test_step_retires_completed_commits_and_runs_their_teardown( + tmp_path, mock_tokenizer, gated +): + rig = _Rig(tmp_path, mock_tokenizer, split=False, commit_blocks=2) + gate = gated(rig) + try: + scheduler = rig.scheduler + _inflight_commit(rig, gate) + _returns_promptly(scheduler._do_abort_request, "r1") + gate.release.set() + scheduler._prefill_commits["r1"][0].result(timeout=20) + + scheduler.step() + assert not scheduler._deferred_teardowns + assert "r1" not in scheduler._boundary_cache_snapshots + finally: + gate.release.set() + rig.close() + + +def test_commits_do_not_queue_behind_a_final_store_of_another_request( + tmp_path, mock_tokenizer +): + rig = _Rig(tmp_path, mock_tokenizer, split=False, commit_blocks=2) + blocker = threading.Event() + try: + scheduler = rig.scheduler + # A long post-finish store occupies the store executor. + scheduler._store_cache_executor.submit(blocker.wait, 30) + _, state = rig.start("r1", PROMPT) + scheduler._step_prefill_chunk(state) + scheduler._step_prefill_chunk(state) + future, _ = scheduler._prefill_commits["r1"] + future.result(timeout=10) # would time out behind the blocked store + scheduler._process_finished_commits() + assert "r1" not in scheduler._prefill_commits + assert rig.table_tokens("r1") == 2 * BLOCK + finally: + blocker.set() + rig.close() + + +def test_same_prompt_reissue_during_a_pending_teardown_keeps_blocks_alive( + tmp_path, mock_tokenizer, gated +): + rig = _Rig(tmp_path, mock_tokenizer, split=False, commit_blocks=2) + gate = gated(rig) + try: + scheduler = rig.scheduler + _inflight_commit(rig, gate) + _returns_promptly(scheduler._do_abort_request, "r1") + gate.release.set() + scheduler._prefill_commits["r1"][0].result(timeout=20) + + # A re-issue matches the committed blocks before the teardown runs. + table, _ = rig.probe(PROMPT) + assert table is not None and table.num_tokens == 2 * BLOCK + scheduler._process_finished_commits() + + for block_id in table.block_ids: + assert rig.paged.allocated_blocks[block_id].ref_count == 1 + assert "r1" not in rig.prefix._request_tables + finally: + gate.release.set() + rig.close() + + +def test_shutdown_completes_pending_teardowns_within_the_bounded_wait( + tmp_path, mock_tokenizer, gated, monkeypatch +): + import omlx.scheduler as scheduler_module + + monkeypatch.setattr(scheduler_module, "PREFILL_COMMIT_SHUTDOWN_WAIT_S", 5.0) + rig = _Rig(tmp_path, mock_tokenizer, split=True, commit_blocks=2) + gate = gated(rig) + scheduler = rig.scheduler + _inflight_commit(rig, gate) + _returns_promptly(scheduler._do_abort_request, "r1") + threading.Timer(0.3, gate.release.set).start() + + scheduler.shutdown() + + assert not scheduler._deferred_teardowns + assert not scheduler._prefill_commits + assert "r1" not in scheduler._boundary_cache_snapshots + + +def test_shutdown_abandons_a_commit_that_never_completes( + tmp_path, mock_tokenizer, gated, monkeypatch +): + import omlx.scheduler as scheduler_module + + monkeypatch.setattr(scheduler_module, "PREFILL_COMMIT_SHUTDOWN_WAIT_S", 0.2) + rig = _Rig(tmp_path, mock_tokenizer, split=True, commit_blocks=2) + gate = gated(rig) + scheduler = rig.scheduler + _inflight_commit(rig, gate) + _returns_promptly(scheduler._do_abort_request, "r1") + + started = time.monotonic() + scheduler.shutdown() + assert time.monotonic() - started < 10 + assert not scheduler._deferred_teardowns + # The snapshot directory is gone even though the commit never finished. + assert not any((tmp_path / "cache").rglob("*r1*")) From 1cca37e252b845ab0b9e926d879e7f19acba7d59 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Thu, 1 Oct 2026 15:06:13 -0600 Subject: [PATCH 05/18] fix(scheduler): drain deferred teardowns on reap, skip held ids, cancel commits at shutdown --- omlx/scheduler.py | 172 ++++++++--- .../test_scheduler_prefill_progress_commit.py | 281 +++++++++++++++++- 2 files changed, 415 insertions(+), 38 deletions(-) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 83c100fa1b..ceb77df011 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -17,6 +17,7 @@ import importlib import inspect import logging +import queue import threading import time from array import array @@ -1341,6 +1342,49 @@ def _is_turboquant_kv_family_cache(cache_obj: Any) -> bool: # A teardown deferred behind a commit that has not finished after this long # is logged once; it stays pending and is dropped at shutdown. PREFILL_COMMIT_STUCK_LOG_S = 60.0 +# Extra bounded wait at shutdown for a commit worker that is inside a store +# call after the cancel flag is set. Past it the stores are left unclosed. +PREFILL_COMMIT_CANCEL_WAIT_S = 10.0 + + +class _DaemonCommitExecutor: + """Single daemon worker thread with the ``submit``/``shutdown`` surface. + + ``ThreadPoolExecutor`` workers are non-daemon and joined at interpreter + exit, so a commit stuck in a store call would hang process exit. This + worker is a daemon: an abandoned commit cannot block exit, and shutdown + only waits for it through the cancel flag and the store lock. + """ + + def __init__(self, thread_name_prefix: str = "omlx-prefill-commit") -> None: + self._queue: queue.SimpleQueue = queue.SimpleQueue() + self._thread = threading.Thread( + target=self._run, name=f"{thread_name_prefix}_0", daemon=True + ) + self._thread.start() + + def _run(self) -> None: + while True: + item = self._queue.get() + if item is None: + return + future, fn, args, kwargs = item + if not future.set_running_or_notify_cancel(): + continue + try: + future.set_result(fn(*args, **kwargs)) + except BaseException as e: # noqa: BLE001 - delivered via the future + future.set_exception(e) + + def submit(self, fn: Callable[..., Any], *args: Any, **kwargs: Any): + future: concurrent.futures.Future = concurrent.futures.Future() + self._queue.put((future, fn, args, kwargs)) + return future + + def shutdown(self, wait: bool = False) -> None: + self._queue.put(None) + if wait: + self._thread.join() def _prefill_commit_blocks(config: Any) -> int: @@ -2233,9 +2277,11 @@ def __init__( self._prefill_commits: dict[str, tuple[concurrent.futures.Future, int]] = {} # Own single-thread executor so commits never queue behind the # post-finish final stores (28GB+ memcpys) on _store_cache_executor. - self._prefill_commit_executor: concurrent.futures.ThreadPoolExecutor | None = ( - None - ) + self._prefill_commit_executor: _DaemonCommitExecutor | None = None + # Shutdown sets the flag; the worker checks it under the lock before + # each store call, and shutdown takes the lock to know none is active. + self._commit_cancelled = threading.Event() + self._commit_store_lock = threading.Lock() # request_id -> destructive teardown steps (release block table, # retire snapshots, ...) postponed until that request's in-flight # commit has finished. Touched on the scheduler thread only. @@ -7739,14 +7785,10 @@ def _prefill_commit_window( self._apply_turboquant_kv_convert(window) return window - def _ensure_prefill_commit_executor( - self, - ) -> concurrent.futures.ThreadPoolExecutor: + def _ensure_prefill_commit_executor(self) -> _DaemonCommitExecutor: executor = self._prefill_commit_executor if executor is None: - executor = concurrent.futures.ThreadPoolExecutor( - max_workers=1, thread_name_prefix="omlx-prefill-commit" - ) + executor = _DaemonCommitExecutor("omlx-prefill-commit") self._prefill_commit_executor = executor return executor @@ -7782,6 +7824,9 @@ def _reap_prefill_commit(self, request_id: str) -> None: ok = False if ok: self._retire_committed_markers(request_id, committed_tokens) + # Draining is part of completion, not of whoever reaps: every path + # (step, finish, next commit) leaves no teardown without its commit. + self._run_deferred_teardowns(request_id) def _inflight_commit_future( self, request_id: str @@ -7836,8 +7881,12 @@ def _process_finished_commits(self) -> None: """ for request_id in list(self._prefill_commits): self._reap_prefill_commit(request_id) - if request_id not in self._prefill_commits: - self._run_deferred_teardowns(request_id) + # Safety net: a deferred teardown whose commit is no longer tracked + # would pin has_requests() and its request id forever. + for request_id in [ + rid for rid in self._deferred_teardowns if rid not in self._prefill_commits + ]: + self._run_deferred_teardowns(request_id) now = time.monotonic() for request_id, since in self._deferred_teardown_since.items(): if ( @@ -7986,19 +8035,27 @@ def _commit_prefill_worker( model_cache_config: Any | None, snapshots: Any | None, ) -> bool: - """Store a committed prefill window; True when the table covers it.""" - self._async_store_cache_worker( - request_id, - tokens, - window_cache, - model_cache_config, - snapshots, - None, - None, - None, - True, - incremental_commit=True, - ) + """Store a committed prefill window; True when the table covers it. + + Cancellation is checked under ``_commit_store_lock`` before the store + call, the only step that touches the stores; shutdown takes that lock + to learn that no store call is active. + """ + with self._commit_store_lock: + if self._commit_cancelled.is_set(): + return False + self._async_store_cache_worker( + request_id, + tokens, + window_cache, + model_cache_config, + snapshots, + None, + None, + None, + True, + incremental_commit=True, + ) table = self.paged_cache_manager.get_block_table(request_id) return bool(table is not None and table.num_tokens >= len(tokens)) @@ -12637,6 +12694,22 @@ def _preflight_safety_rejection( def _schedule_waiting( self, + ) -> tuple[list["Request"], list[RequestOutput]]: + """Admit waiting requests; see ``_schedule_waiting_scan``. + + Requests whose previous run of the same id is still being torn down + behind its prefill commit are set aside while the scan continues, so + one stuck commit never blocks the requests queued behind it; they + return to the front of the queue in their original order. + """ + held: list[Request] = [] + try: + return self._schedule_waiting_scan(held) + finally: + self.waiting.extendleft(reversed(held)) + + def _schedule_waiting_scan( + self, held: list["Request"] ) -> tuple[list["Request"], list[RequestOutput]]: """ Move requests from waiting queue to running. @@ -12772,9 +12845,10 @@ def _schedule_waiting( break if self._teardown_pending(request.request_id): # A previous run of this id is still being torn down behind - # its prefill commit; the head waits (no blocking) so the - # deferred cleanup cannot hit the new run's state. - break + # its prefill commit; only this request waits (no blocking) + # so the deferred cleanup cannot hit the new run's state. + held.append(self.waiting.popleft()) + continue request = self.waiting.popleft() self._cache_freshness_waits.pop(request.request_id, None) @@ -15272,22 +15346,40 @@ def deep_reset(self) -> None: logger.info("Deep reset completed - all caches cleared") - def _shutdown_prefill_commits(self) -> None: - """Finish or safely abandon prefill commits and their teardowns. + def _shutdown_prefill_commits(self) -> bool: + """Finish or cancel prefill commits and their teardowns. + + Returns True when a commit worker is still inside a store call after + the bounded waits; the caller must then leave the stores unclosed. The bounded wait is acceptable here only. A commit that outlives it - is abandoned: its pending teardowns are dropped (the snapshot - directories are removed by ``cleanup_all`` and the process is going - away), and its executor is not joined. + is cancelled: the worker checks ``_commit_cancelled`` under + ``_commit_store_lock`` before its store call, so it bails out cleanly + unless it is already inside one. Shutdown then waits a further + ``PREFILL_COMMIT_CANCEL_WAIT_S`` on that lock. The worker is a daemon + thread, so an abandoned commit cannot block interpreter exit. Pending + teardowns are dropped (``cleanup_all`` removes the snapshot + directories and the process is going away). """ executor = self._prefill_commit_executor stragglers = self._wait_for_prefill_commits(PREFILL_COMMIT_SHUTDOWN_WAIT_S) + store_busy = False if stragglers: + self._commit_cancelled.set() + if self._commit_store_lock.acquire(timeout=PREFILL_COMMIT_CANCEL_WAIT_S): + self._commit_store_lock.release() + else: + store_busy = True logger.warning( - "Abandoning %d prefill commit(s) still running at shutdown " - "(%d pending teardown(s) dropped)", + "Cancelled %d prefill commit(s) still running at shutdown " + "(%d pending teardown(s) dropped)%s", stragglers, len(self._deferred_teardowns), + ( + "; a commit is still inside a store call, stores stay open" + if store_busy + else "" + ), ) elif executor is not None: try: @@ -15301,6 +15393,7 @@ def _shutdown_prefill_commits(self) -> None: if executor is not None: executor.shutdown(wait=False) self._prefill_commit_executor = None + return store_busy def _store_persistence_progress(self): manager = self.paged_ssd_cache_manager @@ -15324,7 +15417,7 @@ def shutdown(self) -> None: # The store-cache gate is a non-blocking counter (#1496), so there is # no step-thread caller to wake here. Inflight futures are drained # below before the executor is asked to shut down. - self._shutdown_prefill_commits() + commit_store_busy = self._shutdown_prefill_commits() # Wait for any inflight async store_cache futures + drain pending # batch_generator removes so the writer thread / underlying paged SSD # cache see all blocks before close(). @@ -15393,7 +15486,7 @@ def shutdown(self) -> None: self._inflight_store_info.clear() self._cache_freshness_waits.clear() self._prefix_cache_prepared.clear() - if self._boundary_snapshot_store is not None: + if self._boundary_snapshot_store is not None and not commit_store_busy: try: self._boundary_snapshot_store.cleanup_all() except Exception as e: @@ -15406,7 +15499,12 @@ def shutdown(self) -> None: self._close_specprefill_draft_cache_manager() self._draft_prefix_cache = None self._specprefill_draft_model = None - if self.paged_ssd_cache_manager is not None: + if self.paged_ssd_cache_manager is not None and commit_store_busy: + logger.error( + "Leaving the paged SSD cache open: a prefill commit worker is " + "still inside a store call" + ) + elif self.paged_ssd_cache_manager is not None: if teardown is not None: teardown.set_phase( "primary_ssd", self.paged_ssd_cache_manager.persistence_progress diff --git a/tests/test_scheduler_prefill_progress_commit.py b/tests/test_scheduler_prefill_progress_commit.py index 8706a50750..0e0dce7545 100644 --- a/tests/test_scheduler_prefill_progress_commit.py +++ b/tests/test_scheduler_prefill_progress_commit.py @@ -114,7 +114,9 @@ def step(self, state, chunks): done = False for _ in range(chunks): done = self.scheduler._step_prefill_chunk(state) - self.drain() + # A commit still in flight makes the next chunk skip its own, so + # settle each one: the commit cadence stays deterministic. + self.drain() return done def drain(self): @@ -910,3 +912,280 @@ def test_shutdown_abandons_a_commit_that_never_completes( assert not scheduler._deferred_teardowns # The snapshot directory is gone even though the commit never finished. assert not any((tmp_path / "cache").rglob("*r1*")) + + +# --- Reaping, admission, shutdown, reset barrier ------------------------------- + + +def _orphans(scheduler): + """Deferred teardowns with neither a tracked commit nor a completion to run on.""" + return [ + rid + for rid in scheduler._deferred_teardowns + if rid not in scheduler._prefill_commits + ] + + +def test_teardowns_drain_when_another_path_reaps_the_commit_first( + tmp_path, mock_tokenizer, gated +): + rig = _Rig(tmp_path, mock_tokenizer, split=True, commit_blocks=2) + gate = gated(rig) + try: + scheduler = rig.scheduler + _inflight_commit(rig, gate) + _returns_promptly(scheduler._do_abort_request, "r1") + assert scheduler._teardown_pending("r1") + gate.release.set() + scheduler._prefill_commits["r1"][0].result(timeout=20) + + # _cleanup_finished-style reap, before _process_finished_commits runs. + assert scheduler._inflight_commit_future("r1") is None + + assert _orphans(scheduler) == [] + assert not scheduler._teardown_pending("r1") + assert "r1" not in scheduler._boundary_cache_snapshots + assert not scheduler._deferred_teardowns # has_requests() is not pinned + finally: + gate.release.set() + rig.close() + + +def test_orphaned_deferred_teardowns_are_swept_at_the_next_step( + tmp_path, mock_tokenizer +): + rig = _Rig(tmp_path, mock_tokenizer, split=False, commit_blocks=2) + try: + scheduler = rig.scheduler + ran = [] + scheduler._deferred_teardowns["ghost"] = [lambda: ran.append("ghost")] + scheduler._deferred_teardown_since["ghost"] = time.monotonic() + + scheduler._process_finished_commits() + + assert ran == ["ghost"] + assert _orphans(scheduler) == [] + assert not scheduler._teardown_pending("ghost") + finally: + rig.close() + + +def test_unrelated_request_is_admitted_behind_a_held_head( + tmp_path, mock_tokenizer, gated +): + rig = _Rig(tmp_path, mock_tokenizer, split=True, commit_blocks=2) + gate = gated(rig) + try: + scheduler = rig.scheduler + request, state = rig.start("r1", PROMPT) + for _ in range(2): + scheduler._step_prefill_chunk(state) + assert gate.entered.wait(20) + _returns_promptly(scheduler._drop_boundary_snapshots_for_request, "r1") + other = Request( + request_id="r2", + prompt=list(range(40, 57)), + sampling_params=SamplingParams(max_tokens=1), + ) + third = Request( + request_id="r3", + prompt=list(range(60, 77)), + sampling_params=SamplingParams(max_tokens=1), + ) + scheduler.add_request(other) + scheduler.add_request(third) + scheduler.waiting.clear() + scheduler.waiting.extend([request, other, third]) + + scheduled, _ = scheduler._schedule_waiting() + + assert [r.request_id for r in scheduled] + [ + r.request_id for r in scheduler.prefilling + ] != [] + queued = [r.request_id for r in scheduler.waiting] + assert queued[0] == "r1" # the held head keeps its place + assert "r2" not in queued # the unrelated request got through + finally: + gate.release.set() + rig.close() + + +class _BlockingStore: + """Replaces store_cache with a call that blocks until released.""" + + def __init__(self, rig, monkeypatch): + self.entered = threading.Event() + self.release = threading.Event() + self.calls = 0 + real = rig.prefix.store_cache + + def blocking(*args, **kwargs): + self.calls += 1 + self.entered.set() + assert self.release.wait(30) + return real(*args, **kwargs) + + monkeypatch.setattr(rig.prefix, "store_cache", blocking) + + +def test_shutdown_cancels_a_commit_that_has_not_reached_the_store( + tmp_path, mock_tokenizer, gated, monkeypatch +): + import omlx.scheduler as scheduler_module + + monkeypatch.setattr(scheduler_module, "PREFILL_COMMIT_SHUTDOWN_WAIT_S", 0.2) + rig = _Rig(tmp_path, mock_tokenizer, split=True, commit_blocks=2) + gate = gated(rig) + scheduler = rig.scheduler + _inflight_commit(rig, gate) + future, _ = scheduler._prefill_commits["r1"] + stores = [] + real_store = rig.prefix.store_cache + monkeypatch.setattr( + rig.prefix, + "store_cache", + lambda *a, **k: (stores.append(1), real_store(*a, **k))[1], + ) + + started = time.monotonic() + scheduler.shutdown() + assert time.monotonic() - started < 10 + + gate.release.set() + assert future.result(timeout=10) is False # bailed out, no store attempted + assert stores == [] + + +def test_shutdown_does_not_close_the_stores_under_an_active_store_call( + tmp_path, mock_tokenizer, monkeypatch +): + import omlx.scheduler as scheduler_module + + monkeypatch.setattr(scheduler_module, "PREFILL_COMMIT_SHUTDOWN_WAIT_S", 0.2) + monkeypatch.setattr(scheduler_module, "PREFILL_COMMIT_CANCEL_WAIT_S", 0.3) + rig = _Rig(tmp_path, mock_tokenizer, split=True, commit_blocks=2) + blocking = _BlockingStore(rig, monkeypatch) + scheduler = rig.scheduler + closed = [] + real_ssd_close = rig.ssd.close + real_boundary_shutdown = rig.boundary.shutdown + monkeypatch.setattr( + rig.ssd, + "close", + lambda *a, **k: (closed.append("ssd"), real_ssd_close(*a, **k)), + ) + monkeypatch.setattr( + rig.boundary, + "shutdown", + lambda *a, **k: (closed.append("boundary"), real_boundary_shutdown(*a, **k)), + ) + try: + _, state = rig.start("r1", PROMPT) + for _ in range(2): + scheduler._step_prefill_chunk(state) + assert blocking.entered.wait(20) + + started = time.monotonic() + scheduler.shutdown() + assert time.monotonic() - started < 10 # bounded + assert closed == [] # worker is still inside the store call + finally: + blocking.release.set() + time.sleep(0.2) + real_ssd_close() + real_boundary_shutdown() + + +def test_commit_executor_threads_cannot_block_interpreter_exit( + tmp_path, mock_tokenizer +): + rig = _Rig(tmp_path, mock_tokenizer, split=False, commit_blocks=2) + try: + executor = rig.scheduler._ensure_prefill_commit_executor() + seen = executor.submit(lambda: threading.current_thread()).result(timeout=10) + assert seen.daemon + assert seen.name.startswith("omlx-prefill-commit") + finally: + rig.close() + + +def test_reset_runs_deferred_teardowns_before_clearing_state( + tmp_path, mock_tokenizer, gated, monkeypatch +): + import omlx.scheduler as scheduler_module + + monkeypatch.setattr(scheduler_module, "FATAL_TEARDOWN_TIMEOUT_S", 10.0) + rig = _Rig(tmp_path, mock_tokenizer, split=True, commit_blocks=2) + gate = gated(rig) + scheduler = rig.scheduler + try: + _inflight_commit(rig, gate) + _returns_promptly(scheduler._do_abort_request, "r1") + events = [] + real_cleanup = rig.boundary.cleanup_request + real_clear = rig.prefix.clear + monkeypatch.setattr( + rig.boundary, + "cleanup_request", + lambda rid: (events.append("teardown"), real_cleanup(rid))[1], + ) + monkeypatch.setattr( + rig.prefix, "clear", lambda: (events.append("clear"), real_clear())[1] + ) + threading.Timer(0.3, gate.release.set).start() + + scheduler.reset() + + assert events[:2] == ["teardown", "clear"] + assert not scheduler._deferred_teardowns + assert not scheduler._prefill_commits + finally: + gate.release.set() + rig.close() + + +def test_reset_is_fatal_when_a_commit_outlives_the_barrier( + tmp_path, mock_tokenizer, gated, monkeypatch +): + import omlx.scheduler as scheduler_module + + monkeypatch.setattr(scheduler_module, "FATAL_TEARDOWN_TIMEOUT_S", 0.2) + fatal = [] + monkeypatch.setattr(scheduler_module, "fatal_exit", lambda msg: fatal.append(msg)) + rig = _Rig(tmp_path, mock_tokenizer, split=True, commit_blocks=2) + gate = gated(rig) + scheduler = rig.scheduler + try: + _inflight_commit(rig, gate) + scheduler.reset() + assert len(fatal) == 1 + assert "prefill commit" in fatal[0] + assert "r1" in scheduler._prefill_commits # nothing was cleared + finally: + gate.release.set() + rig.close() + + +def test_stuck_teardown_warning_is_logged_once( + tmp_path, mock_tokenizer, gated, monkeypatch, caplog +): + import logging + + import omlx.scheduler as scheduler_module + + monkeypatch.setattr(scheduler_module, "PREFILL_COMMIT_STUCK_LOG_S", 0.0) + rig = _Rig(tmp_path, mock_tokenizer, split=True, commit_blocks=2) + gate = gated(rig) + scheduler = rig.scheduler + try: + _inflight_commit(rig, gate) + _returns_promptly(scheduler._do_abort_request, "r1") + with caplog.at_level(logging.WARNING, logger="omlx.scheduler"): + for _ in range(3): + scheduler._process_finished_commits() + stuck = [r for r in caplog.records if "still waits" in r.getMessage()] + assert len(stuck) == 1 + assert "r1" in stuck[0].getMessage() + finally: + gate.release.set() + rig.close() From 2be13399bd2dc3fa046b6ea64fbf673b2690ac16 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Thu, 1 Oct 2026 15:29:50 -0600 Subject: [PATCH 06/18] fix(scheduler): bound the final store's wait on an in-flight prefill 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. --- omlx/scheduler.py | 50 ++++++++++++- .../test_scheduler_prefill_progress_commit.py | 70 +++++++++++++++++++ 2 files changed, 118 insertions(+), 2 deletions(-) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index ceb77df011..46ecbff71d 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -1345,6 +1345,10 @@ def _is_turboquant_kv_family_cache(cache_obj: Any) -> bool: # Extra bounded wait at shutdown for a commit worker that is inside a store # call after the cancel flag is set. Past it the stores are left unclosed. PREFILL_COMMIT_CANCEL_WAIT_S = 10.0 +# Bound on the final-store worker waiting for the request's in-flight commit. +# Past it the final store is skipped so a stuck commit cannot hold the store +# worker (and the gate slots queued behind it). +PREFILL_COMMIT_FINAL_STORE_WAIT_S = 120.0 class _DaemonCommitExecutor: @@ -2288,6 +2292,10 @@ def __init__( self._deferred_teardowns: dict[str, list[Callable[[], None]]] = {} self._deferred_teardown_since: dict[str, float] = {} self._stuck_teardown_logged: set[str] = set() + # Final stores skipped because the request's commit never ended within + # PREFILL_COMMIT_FINAL_STORE_WAIT_S. Added on the store worker (GIL-atomic + # set.add), consumed by _drain_pending_async_removes on the scheduler thread. + self._skipped_final_stores: set[str] = set() self.requests: dict[str, Request] = {} # All requests by ID self.finished_req_ids: set[str] = set() # Recently finished self._generation_overflow_recovery_ids: set[str] = set() @@ -2886,7 +2894,21 @@ def _async_store_cache_worker( """ self._store_cache_thread_id = threading.get_ident() if after_commit is not None: - concurrent.futures.wait([after_commit]) + done, _pending = concurrent.futures.wait( + [after_commit], timeout=PREFILL_COMMIT_FINAL_STORE_WAIT_S + ) + if not done: + # Skip this final store; table and snapshot teardown stays + # deferred behind the commit (scheduler thread), the gate slot + # is released when the drain sees this future done. + logger.warning( + "Skipping final store for %s: its prefill commit did not " + "finish within %.0fs", + request_id, + PREFILL_COMMIT_FINAL_STORE_WAIT_S, + ) + self._skipped_final_stores.add(request_id) + return window_kwargs = {"cache_covers_suffix_only": True} if incremental_commit else {} try: # Hold _mx_buffer_access_lock across the worker's mx-buffer @@ -2939,6 +2961,21 @@ def _async_store_cache_worker( except Exception as e: logger.warning("Async store_cache failed for %s: %s", request_id, e) + def _skipped_store_teardown(self, request_id: str) -> Callable[[], None]: + """Teardown for a request whose final store was skipped (stuck commit).""" + + def teardown() -> None: + if self._boundary_snapshot_store is not None: + self._boundary_snapshot_store.cleanup_request(request_id) + if self.paged_cache_manager is not None: + block_table = self.paged_cache_manager.get_block_table(request_id) + if block_table: + self.paged_cache_manager.release_for_eviction(block_table.block_ids) + if self.block_aware_cache is not None: + self.block_aware_cache.clear_request_entry(request_id) + + return teardown + def _drain_pending_async_removes(self) -> bool: """Process deferred batch_generator.remove() calls from prior steps. @@ -2998,7 +3035,15 @@ def _drain_pending_async_removes(self) -> bool: # delete now that the future has completed. Cleanup was # deferred from _cleanup_finished to avoid racing the worker's # boundary_snapshot_store.load() calls with rmtree. - if self._boundary_snapshot_store is not None: + if request_id in self._skipped_final_stores: + # The final store never ran: the stuck commit may still + # read the snapshots and use the table, so both are torn + # down once it ends, exactly as the worker would have. + self._skipped_final_stores.discard(request_id) + self._after_commit( + request_id, self._skipped_store_teardown(request_id) + ) + elif self._boundary_snapshot_store is not None: self._boundary_snapshot_store.cleanup_request(request_id) # Worker no longer holds extracted_cache — pop request from # self.requests and drop the cache buffer references so MLX @@ -15265,6 +15310,7 @@ def reset(self) -> None: self._deferred_teardowns.clear() self._deferred_teardown_since.clear() self._stuck_teardown_logged.clear() + self._skipped_final_stores.clear() self._prefill_commits.clear() self._cache_freshness_waits.clear() self._prefix_cache_prepared.clear() diff --git a/tests/test_scheduler_prefill_progress_commit.py b/tests/test_scheduler_prefill_progress_commit.py index 0e0dce7545..2bf88a5dc6 100644 --- a/tests/test_scheduler_prefill_progress_commit.py +++ b/tests/test_scheduler_prefill_progress_commit.py @@ -1189,3 +1189,73 @@ def test_stuck_teardown_warning_is_logged_once( finally: gate.release.set() rig.close() + + +# --- Bounded wait of the final store on an in-flight commit -------------------- + + +def test_stuck_commit_times_out_the_final_store_and_frees_the_slot( + tmp_path, mock_tokenizer, monkeypatch, gated, caplog +): + """A commit that never ends must not hold the final-store worker or gate. + + The final store is skipped (logged once), the store-gate slot is released, + and a later request's final store proceeds on the same worker thread. + """ + import logging + + import omlx.scheduler as scheduler_module + + monkeypatch.setattr(scheduler_module, "PREFILL_COMMIT_FINAL_STORE_WAIT_S", 0.3) + rig = _Rig(tmp_path, mock_tokenizer, split=False, commit_blocks=2) + gate = gated(rig) + try: + scheduler = rig.scheduler + request, state = rig.start("r1", PROMPT) + while not scheduler._step_prefill_chunk(state): + pass + assert gate.entered.wait(20) + finished = _decode_to_finish(rig, request, state) + + class _Gate: + submitted = 0 + done = 0 + + def note_submitted(self): + self.submitted += 1 + + def note_done(self): + self.done += 1 + + store_gate = _Gate() + scheduler._store_cache_gate = store_gate + with caplog.at_level(logging.WARNING, logger="omlx.scheduler"): + scheduler._cleanup_finished(finished) + scheduler._inflight_store_futures["r1"].result(timeout=10) + scheduler._drain_pending_async_removes() + + # Skipped, logged once, slot released although the commit still runs. + timeouts = [r for r in caplog.records if "final store" in r.getMessage()] + assert len(timeouts) == 1 + assert store_gate.submitted == 1 and store_gate.done == 1 + assert "r1" not in scheduler._inflight_store_futures + assert not scheduler._pending_async_removes + + # Table state is released through the deferred teardown once it ends. + assert scheduler._teardown_pending("r1") + gate.release.set() + rig.drain() + assert not scheduler._teardown_pending("r1") + assert "r1" not in rig.prefix._request_tables + # The blocks the commit stored stay reusable by a re-issue. + table, _ = rig.probe(PROMPT) + assert table is not None and table.num_tokens >= BLOCK + + # A later final store proceeds. + request2, state2 = rig.start("r2", list(range(40, 57))) + _finish(rig, request2, state2) + table, _ = rig.probe(list(range(40, 57))) + assert table is not None and table.num_tokens == 4 * BLOCK + finally: + gate.release.set() + rig.close() From beea8719bdf9b02d460a91c4ee9cae078d1e2483 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Fri, 2 Oct 2026 09:17:11 -0600 Subject: [PATCH 07/18] refactor(scheduler): move the prefill commit executor into its own module 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. --- omlx/prefill_commit_executor.py | 54 +++++++++++++++++++++++++++++++++ omlx/scheduler.py | 42 +------------------------ 2 files changed, 55 insertions(+), 41 deletions(-) create mode 100644 omlx/prefill_commit_executor.py diff --git a/omlx/prefill_commit_executor.py b/omlx/prefill_commit_executor.py new file mode 100644 index 0000000000..49550b4f63 --- /dev/null +++ b/omlx/prefill_commit_executor.py @@ -0,0 +1,54 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Single daemon-thread executor for incremental prefill commits. + +Kept out of ``scheduler.py`` so the scheduler module has exactly one +``shutdown`` definition (``Scheduler.shutdown``). +""" + +from __future__ import annotations + +import concurrent.futures +import queue +import threading +from collections.abc import Callable +from typing import Any + + +class DaemonCommitExecutor: + """Single daemon worker thread with the ``submit``/``shutdown`` surface. + + ``ThreadPoolExecutor`` workers are non-daemon and joined at interpreter + exit, so a commit stuck in a store call would hang process exit. This + worker is a daemon: an abandoned commit cannot block exit, and shutdown + only waits for it through the cancel flag and the store lock. + """ + + def __init__(self, thread_name_prefix: str = "omlx-prefill-commit") -> None: + self._queue: queue.SimpleQueue = queue.SimpleQueue() + self._thread = threading.Thread( + target=self._run, name=f"{thread_name_prefix}_0", daemon=True + ) + self._thread.start() + + def _run(self) -> None: + while True: + item = self._queue.get() + if item is None: + return + future, fn, args, kwargs = item + if not future.set_running_or_notify_cancel(): + continue + try: + future.set_result(fn(*args, **kwargs)) + except BaseException as e: # noqa: BLE001 - delivered via the future + future.set_exception(e) + + def submit(self, fn: Callable[..., Any], *args: Any, **kwargs: Any): + future: concurrent.futures.Future = concurrent.futures.Future() + self._queue.put((future, fn, args, kwargs)) + return future + + def shutdown(self, wait: bool = False) -> None: + self._queue.put(None) + if wait: + self._thread.join() diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 46ecbff71d..a7462066e4 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -17,7 +17,6 @@ import importlib import inspect import logging -import queue import threading import time from array import array @@ -78,6 +77,7 @@ clamp_prefill_chunk_to_boundary, should_emit_prefill_boundary, ) +from .prefill_commit_executor import DaemonCommitExecutor as _DaemonCommitExecutor from .prefill_progress import get_prefill_tracker from .prefill_transient_tracker import PrefillTransientTracker from .request import Request, RequestOutput, RequestStatus, SamplingParams @@ -1351,46 +1351,6 @@ def _is_turboquant_kv_family_cache(cache_obj: Any) -> bool: PREFILL_COMMIT_FINAL_STORE_WAIT_S = 120.0 -class _DaemonCommitExecutor: - """Single daemon worker thread with the ``submit``/``shutdown`` surface. - - ``ThreadPoolExecutor`` workers are non-daemon and joined at interpreter - exit, so a commit stuck in a store call would hang process exit. This - worker is a daemon: an abandoned commit cannot block exit, and shutdown - only waits for it through the cancel flag and the store lock. - """ - - def __init__(self, thread_name_prefix: str = "omlx-prefill-commit") -> None: - self._queue: queue.SimpleQueue = queue.SimpleQueue() - self._thread = threading.Thread( - target=self._run, name=f"{thread_name_prefix}_0", daemon=True - ) - self._thread.start() - - def _run(self) -> None: - while True: - item = self._queue.get() - if item is None: - return - future, fn, args, kwargs = item - if not future.set_running_or_notify_cancel(): - continue - try: - future.set_result(fn(*args, **kwargs)) - except BaseException as e: # noqa: BLE001 - delivered via the future - future.set_exception(e) - - def submit(self, fn: Callable[..., Any], *args: Any, **kwargs: Any): - future: concurrent.futures.Future = concurrent.futures.Future() - self._queue.put((future, fn, args, kwargs)) - return future - - def shutdown(self, wait: bool = False) -> None: - self._queue.put(None) - if wait: - self._thread.join() - - def _prefill_commit_blocks(config: Any) -> int: """``prefill_progress_commit_blocks`` of a config, 0 when unset or invalid.""" value = getattr(config, "prefill_progress_commit_blocks", 0) From e37bdfc83b65a79e857b3bd005b1208bd6223394 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Thu, 1 Oct 2026 15:34:03 -0600 Subject: [PATCH 08/18] feat(enforcer): request a prefill park before aborting at hard pressure 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. --- omlx/process_memory_enforcer.py | 74 +++++++++++++++++ omlx/scheduler.py | 5 ++ omlx/settings.py | 43 ++++++++++ tests/test_process_memory_enforcer.py | 110 ++++++++++++++++++++++++++ tests/test_settings.py | 59 ++++++++++++++ 5 files changed, 291 insertions(+) diff --git a/omlx/process_memory_enforcer.py b/omlx/process_memory_enforcer.py index e021adee0b..b0e9448d21 100644 --- a/omlx/process_memory_enforcer.py +++ b/omlx/process_memory_enforcer.py @@ -468,6 +468,9 @@ def __init__( # prefill chunk / step boundary. See the grace check in # _check_and_enforce. self._pressure_reclaim_grace_polls: int = 0 + # Consecutive hard-pressure polls whose abort was deferred in favor of + # parking a prefill victim. See _request_scheduler_park. + self._park_deferred_polls: int = 0 # Last value passed to mx.set_wired_limit (0 if not yet applied # or the call failed). Used by the admin dashboard to surface a # warning when the kernel iogpu.wired_limit_mb is below this. @@ -1271,6 +1274,10 @@ def _shrink_hot_cache_by( # while a reclaimable pool drains. Prefill chunks run ~5s at full step # size, so 5 one-second polls cover at least one chunk boundary. _PRESSURE_RECLAIM_GRACE_POLLS_MAX = 5 + # Max consecutive hard-pressure polls the abort is deferred because a + # scheduler reports a prefill victim to park (or one just parked). Bounds + # the deferral if the scheduler never gets to act on the request. + _PARK_DEFER_POLLS_MAX = 30 def _pool_bytes(self) -> int: """MLX buffer-pool size, 0 when unreadable (mocked mx in tests).""" @@ -1321,6 +1328,45 @@ def _request_scheduler_cache_reclaim(self, freed_hot: int) -> int: ) return requested + def _request_scheduler_park(self) -> int: + """Ask each scheduler to park one prefill victim instead of aborting. + + Sets a GIL-atomic flag on the scheduler; the park itself runs on the + inference thread at the next step boundary, so the enforcer never + touches request or Metal state. A scheduler answers ``True`` only when + a victim is parkable or a park is still settling; any other answer + (park disabled, nothing parkable, no API) leaves the legacy abort in + place. Returns the number of schedulers that accepted. + """ + accepted = 0 + for entry in self._engine_pool._entries.values(): + scheduler = self._resolve_scheduler(entry) + request = getattr(scheduler, "request_park_prefill", None) + if not callable(request): + continue + try: + if request() is True: + accepted += 1 + except Exception as exc: # noqa: BLE001 + logger.warning("Prefill park request failed: %s", exc) + return accepted + + def _note_pressure_poll(self, level: str) -> None: + """Report this poll's pressure level to every scheduler. + + Schedulers count consecutive ``ok`` polls to decide when parked + requests may resume (hysteresis). Called once per enforcement tick. + """ + for entry in self._engine_pool._entries.values(): + scheduler = self._resolve_scheduler(entry) + note = getattr(scheduler, "note_pressure_poll", None) + if not callable(note): + continue + try: + note(level) + except Exception as exc: # noqa: BLE001 + logger.debug("Pressure poll report failed: %s", exc) + def get_pressure_level(self) -> str: """Return cached pressure level: 'ok', 'soft', or 'hard'. @@ -1692,6 +1738,8 @@ async def _check_and_enforce(self) -> None: self._pressure_level = "ok" self._over_ceiling_polls = 0 self._pressure_reclaim_grace_polls = 0 + self._park_deferred_polls = 0 + self._note_pressure_poll("ok") return current = self._current_usage_bytes() @@ -1717,6 +1765,10 @@ async def _check_and_enforce(self) -> None: else: new_level = "hard" + self._note_pressure_poll(new_level) + if new_level != "hard": + self._park_deferred_polls = 0 + if new_level == "ok": # The pressure episode ended (drain worked or the load finished): # the next one gets a fresh reclaim-grace budget. Must happen @@ -1802,6 +1854,28 @@ async def _check_and_enforce(self) -> None: self._walk_store_cache_caps() return + # Park before abort: a scheduler with a parkable prefill victim pauses + # it (work already done survives in the prefix cache) and the abort + # below only runs when nothing is left to park, the deferral budget is + # spent, or pressure is an emergency (beyond the real ceiling). + if ( + new_level == "hard" + and not emergency + and self._park_deferred_polls < self._PARK_DEFER_POLLS_MAX + ): + parked_on = self._request_scheduler_park() + if parked_on: + self._park_deferred_polls += 1 + logger.info( + "Hard memory pressure: parking a prefill victim on %d " + "scheduler(s) instead of aborting (poll %d/%d)", + parked_on, + self._park_deferred_polls, + self._PARK_DEFER_POLLS_MAX, + ) + self._walk_store_cache_caps() + return + # Recover below soft regardless of level — prevents oscillation # at the boundary. target = soft diff --git a/omlx/scheduler.py b/omlx/scheduler.py index a7462066e4..e597c02eea 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -1873,6 +1873,11 @@ class SchedulerConfig: # completed blocks, and a re-issue of the same prompt resumes from the last # committed block boundary instead of prefilling from token zero. prefill_progress_commit_blocks: int = 0 + # Park (pause without error) the most recent prefilling request under hard + # memory pressure instead of aborting; see Scheduler.request_park_prefill. + memory_pressure_park: bool = False + max_parks_per_request: int = 3 + park_resume_ok_polls: int = 3 # Paged cache settings (internal defaults) paged_cache_block_size: int = 256 # Tokens per block diff --git a/omlx/settings.py b/omlx/settings.py index d363d0f111..b468b08366 100644 --- a/omlx/settings.py +++ b/omlx/settings.py @@ -355,6 +355,15 @@ class SchedulerSettings: # prompt is still prefilling, so an aborted or re-issued request resumes from # the last committed block instead of token zero. 0 disables it. prefill_progress_commit_blocks: int = 0 + # Under hard memory pressure, pause (park) the most recent prefilling + # request instead of aborting everything; it re-queues without an error + # and resumes from its last committed prefix once pressure has cleared. + # Best with prefill_progress_commit_blocks > 0 (otherwise it resumes cold). + memory_pressure_park: bool = False + # Parks a single request may take before it falls back to the abort. + max_parks_per_request: int = 3 + # Consecutive "ok" pressure polls before parked requests may resume. + park_resume_ok_polls: int = 3 def to_dict(self) -> dict[str, Any]: """Convert to dictionary.""" @@ -383,6 +392,13 @@ def from_dict(cls, data: dict[str, Any]) -> SchedulerSettings: or commit_blocks < 0 ): commit_blocks = 0 + + def positive_int(key: str, default: int) -> int: + value = data.get(key, default) + if not isinstance(value, int) or isinstance(value, bool) or value < 1: + return default + return value + return cls( max_concurrent_requests=value, embedding_batch_size=embedding_batch_size, @@ -390,6 +406,9 @@ def from_dict(cls, data: dict[str, Any]) -> SchedulerSettings: prefill_priority=prefill_priority, decode_fairness=bool(data.get("decode_fairness", True)), prefill_progress_commit_blocks=commit_blocks, + memory_pressure_park=data.get("memory_pressure_park") is True, + max_parks_per_request=positive_int("max_parks_per_request", 3), + park_resume_ok_polls=positive_int("park_resume_ok_polls", 3), ) @@ -1280,6 +1299,17 @@ def _apply_env_overrides(self) -> None: f"Invalid OMLX_PREFILL_PROGRESS_COMMIT_BLOCKS value: " f"{commit_blocks}" ) + if park := os.getenv("OMLX_MEMORY_PRESSURE_PARK"): + self.scheduler.memory_pressure_park = park.lower() in ("true", "1", "yes") + for env_name, attr in ( + ("OMLX_MAX_PARKS_PER_REQUEST", "max_parks_per_request"), + ("OMLX_PARK_RESUME_OK_POLLS", "park_resume_ok_polls"), + ): + if raw := os.getenv(env_name): + try: + setattr(self.scheduler, attr, int(raw)) + except ValueError: + logger.warning(f"Invalid {env_name} value: {raw}") # Cache settings if cache_enabled := os.getenv("OMLX_CACHE_ENABLED"): @@ -1796,6 +1826,16 @@ def validate(self) -> list[str]: f"Invalid prefill_progress_commit_blocks: " f"{self.scheduler.prefill_progress_commit_blocks} (must be >= 0)" ) + if self.scheduler.max_parks_per_request < 1: + errors.append( + f"Invalid max_parks_per_request: " + f"{self.scheduler.max_parks_per_request} (must be >= 1)" + ) + if self.scheduler.park_resume_ok_polls < 1: + errors.append( + f"Invalid park_resume_ok_polls: " + f"{self.scheduler.park_resume_ok_polls} (must be >= 1)" + ) # Cache validation if self.cache.gdn_ssd_split_enabled is True and self.cache.hot_cache_only: @@ -1974,6 +2014,9 @@ def to_scheduler_config(self) -> SchedulerConfig: prefill_progress_commit_blocks=( self.scheduler.prefill_progress_commit_blocks ), + memory_pressure_park=self.scheduler.memory_pressure_park, + max_parks_per_request=self.scheduler.max_parks_per_request, + park_resume_ok_polls=self.scheduler.park_resume_ok_polls, initial_cache_blocks=self.cache.initial_cache_blocks, paged_ssd_cache_dir=str(ssd_dir) if ssd_dir else None, hot_cache_only=self.cache.hot_cache_only, diff --git a/tests/test_process_memory_enforcer.py b/tests/test_process_memory_enforcer.py index 14c1bbbd18..6205d56b08 100644 --- a/tests/test_process_memory_enforcer.py +++ b/tests/test_process_memory_enforcer.py @@ -3378,3 +3378,113 @@ async def test_image_cache_reclaim_remeasures_retained_request_memory(mock_engin assert active_image.getpixel((0, 0)) == (0, 0, 255) finally: images.clear_image_decode_cache() + + +class TestPrefillParkRequest: + """Hard pressure asks the scheduler to park a prefill victim before it + falls back to the legacy abort. Park off (the scheduler answers False or + has no park API) keeps the abort exactly as before.""" + + @pytest.fixture + def enforcer(self, mock_engine_pool): + # Two watermarks: hard (95 GB) sits below the 100 GB ceiling, so + # repeated hard polls are not escalated to emergency pressure. + return _make_enforcer( + mock_engine_pool, + ceiling=100 * 1024**3, + soft_threshold=0.85, + hard_threshold=0.95, + ) + + def _setup(self, enforcer, park_answer): + engine = MagicMock() + engine.has_active_requests.return_value = False + engine.abort_all_requests = AsyncMock(return_value=1) + scheduler = SimpleNamespace( + request_park_prefill=MagicMock(return_value=park_answer), + note_pressure_poll=MagicMock(), + adjust_store_cache_cap=MagicMock(), + ) + engine.scheduler = scheduler + entry = _make_entry("big-model", engine=engine) + entry.in_use = 1 + enforcer._engine_pool._entries = {"big-model": entry} + enforcer._engine_pool._find_lru_victim.return_value = None + return engine, scheduler + + async def _tick(self, enforcer, usage=96 * 1024**3): + with patch("omlx.process_memory_enforcer.mx") as mock_mx: + mock_mx.get_active_memory.return_value = usage + mock_mx.get_cache_memory.return_value = 0 + await enforcer._check_and_enforce() + + @pytest.mark.asyncio + async def test_park_disabled_still_aborts_as_before(self, enforcer): + engine, scheduler = self._setup(enforcer, park_answer=False) + await self._tick(enforcer) + scheduler.request_park_prefill.assert_called_once() + engine.abort_all_requests.assert_awaited_once() + + @pytest.mark.asyncio + async def test_scheduler_without_park_api_aborts_as_before(self, enforcer): + engine, scheduler = self._setup(enforcer, park_answer=False) + del scheduler.request_park_prefill + await self._tick(enforcer) + engine.abort_all_requests.assert_awaited_once() + + @pytest.mark.asyncio + async def test_parkable_victim_defers_the_abort(self, enforcer): + engine, scheduler = self._setup(enforcer, park_answer=True) + await self._tick(enforcer) + scheduler.request_park_prefill.assert_called_once() + engine.abort_all_requests.assert_not_awaited() + enforcer._engine_pool._unload_engine.assert_not_awaited() + + @pytest.mark.asyncio + async def test_abort_after_nothing_is_left_to_park(self, enforcer): + engine, scheduler = self._setup(enforcer, park_answer=True) + await self._tick(enforcer) + engine.abort_all_requests.assert_not_awaited() + scheduler.request_park_prefill.return_value = False + await self._tick(enforcer) + engine.abort_all_requests.assert_awaited_once() + + @pytest.mark.asyncio + async def test_a_scheduler_that_never_parks_cannot_defer_forever(self, enforcer): + engine, scheduler = self._setup(enforcer, park_answer=True) + for _ in range(enforcer._PARK_DEFER_POLLS_MAX): + await self._tick(enforcer) + engine.abort_all_requests.assert_not_awaited() + await self._tick(enforcer) + engine.abort_all_requests.assert_awaited_once() + + @pytest.mark.asyncio + async def test_emergency_pressure_aborts_without_parking(self, enforcer): + engine, scheduler = self._setup(enforcer, park_answer=True) + await self._tick(enforcer, usage=103 * 1024**3) + scheduler.request_park_prefill.assert_not_called() + engine.abort_all_requests.assert_awaited() + + @pytest.mark.asyncio + async def test_a_truthy_non_bool_answer_is_not_a_park(self, enforcer): + engine, scheduler = self._setup(enforcer, park_answer=MagicMock()) + await self._tick(enforcer) + engine.abort_all_requests.assert_awaited_once() + + @pytest.mark.asyncio + async def test_park_deferral_budget_resets_when_pressure_clears(self, enforcer): + engine, scheduler = self._setup(enforcer, park_answer=True) + for _ in range(3): + await self._tick(enforcer) + assert enforcer._park_deferred_polls == 3 + await self._tick(enforcer, usage=1 * 1024**3) + assert enforcer._park_deferred_polls == 0 + + @pytest.mark.asyncio + async def test_every_poll_reports_its_level_to_the_scheduler(self, enforcer): + engine, scheduler = self._setup(enforcer, park_answer=False) + await self._tick(enforcer, usage=1 * 1024**3) + scheduler.note_pressure_poll.assert_called_with("ok") + await self._tick(enforcer, usage=96 * 1024**3) + scheduler.note_pressure_poll.assert_called_with("hard") + assert scheduler.note_pressure_poll.call_count == 2 diff --git a/tests/test_settings.py b/tests/test_settings.py index b4218c8366..5def31bfa6 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -395,6 +395,9 @@ def test_to_dict(self): "prefill_priority": "context", "decode_fairness": True, "prefill_progress_commit_blocks": 0, + "memory_pressure_park": False, + "max_parks_per_request": 3, + "park_resume_ok_polls": 3, } def test_prefill_progress_commit_blocks_from_dict(self): @@ -428,6 +431,62 @@ def test_prefill_progress_commit_blocks_must_not_be_negative(self, tmp_path): settings.scheduler.prefill_progress_commit_blocks = -1 assert any("prefill_progress_commit_blocks" in e for e in settings.validate()) + def test_park_settings_defaults_and_round_trip(self): + """Park is off by default; valid values round-trip; junk falls back.""" + defaults = SchedulerSettings.from_dict({}) + assert defaults.memory_pressure_park is False + assert defaults.max_parks_per_request == 3 + assert defaults.park_resume_ok_polls == 3 + custom = SchedulerSettings.from_dict( + { + "memory_pressure_park": True, + "max_parks_per_request": 5, + "park_resume_ok_polls": 1, + } + ) + assert custom.memory_pressure_park is True + assert custom.max_parks_per_request == 5 + assert custom.park_resume_ok_polls == 1 + for bad in ("many", None, -1, 0, True): + junk = SchedulerSettings.from_dict( + {"max_parks_per_request": bad, "park_resume_ok_polls": bad} + ) + assert junk.max_parks_per_request == 3 + assert junk.park_resume_ok_polls == 3 + + def test_park_settings_reach_scheduler_config(self, tmp_path): + settings = GlobalSettings(base_path=tmp_path) + config = settings.to_scheduler_config() + assert config.memory_pressure_park is False + assert (config.max_parks_per_request, config.park_resume_ok_polls) == (3, 3) + settings.scheduler.memory_pressure_park = True + settings.scheduler.max_parks_per_request = 2 + settings.scheduler.park_resume_ok_polls = 4 + config = settings.to_scheduler_config() + assert config.memory_pressure_park is True + assert (config.max_parks_per_request, config.park_resume_ok_polls) == (2, 4) + + def test_park_settings_env_override(self, tmp_path): + env = { + "OMLX_MEMORY_PRESSURE_PARK": "true", + "OMLX_MAX_PARKS_PER_REQUEST": "7", + "OMLX_PARK_RESUME_OK_POLLS": "2", + } + with patch.dict(os.environ, env, clear=False): + settings = GlobalSettings.load(base_path=tmp_path) + assert settings.scheduler.memory_pressure_park is True + assert settings.scheduler.max_parks_per_request == 7 + assert settings.scheduler.park_resume_ok_polls == 2 + + def test_park_settings_validation(self, tmp_path): + settings = GlobalSettings(base_path=tmp_path) + assert not any("park" in e for e in settings.validate()) + settings.scheduler.max_parks_per_request = 0 + settings.scheduler.park_resume_ok_polls = 0 + errors = settings.validate() + assert any("max_parks_per_request" in e for e in errors) + assert any("park_resume_ok_polls" in e for e in errors) + def test_decode_fairness_from_dict(self): """Defaults on; explicit false round-trips.""" assert SchedulerSettings.from_dict({}).decode_fairness is True From 21dc1902e5a4f8e7962ba3f22343b92591028bfd Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Thu, 1 Oct 2026 15:42:49 -0600 Subject: [PATCH 09/18] feat(scheduler): park a chunked prefill under memory pressure instead 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. --- docs/TESTING.md | 6 + omlx/cache/paged_ssd_cache.py | 54 +- omlx/engine_core.py | 8 +- omlx/request.py | 6 + omlx/scheduler.py | 296 +++++++++ tests/test_engine_core.py | 25 + tests/test_scheduler_park.py | 585 ++++++++++++++++++ .../test_scheduler_prefill_progress_commit.py | 12 +- 8 files changed, 987 insertions(+), 5 deletions(-) create mode 100644 tests/test_scheduler_park.py diff --git a/docs/TESTING.md b/docs/TESTING.md index aeb9da1a04..7706308202 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -234,3 +234,9 @@ For a real-server comparison, use the same model, prompts and cache state on mai Run `python -m pytest -q tests/test_scheduler_prefill_progress_commit.py tests/test_settings.py -k "prefill_progress or commit"` to check `scheduler.prefill_progress_commit_blocks` (also `OMLX_PREFILL_PROGRESS_COMMIT_BLOCKS`; 0 = off, the default). The cases drive the real chunked and external prefill loops on a small initialized Qwen3.5 hybrid model (inline and split-GDN snapshots) and a small dense model, against real paged-SSD, boundary-snapshot and prefix stores, and compare restored-prefix logits with a cold forward pass. They cover commits every N blocks, a request aborted mid-prefill whose same-prompt re-issue resumes from the last committed boundary, completion after commits (same stored prefix, no duplicate blocks or leftover snapshot markers), a commit window longer than the restored prefix, TurboQuant windows matching whole-prefix conversion bit for bit, the memory-pressure skip, and the cold retry after a prefill memory failure. Mocked tests do not replace hardware validation: with a real model, abort a long prompt mid-prefill (for example with a low memory ceiling and two concurrent prompts), re-issue it, and check that the log reports a prefix cache restore at the last committed boundary instead of a full prefill. + +# Memory-pressure park tests + +Run `python -m pytest -q tests/test_scheduler_park.py tests/test_process_memory_enforcer.py tests/test_settings.py -k "park or Park"` to check `scheduler.memory_pressure_park` (also `OMLX_MEMORY_PRESSURE_PARK`; off by default), `scheduler.max_parks_per_request` (`OMLX_MAX_PARKS_PER_REQUEST`, default 3) and `scheduler.park_resume_ok_polls` (`OMLX_PARK_RESUME_OK_POLLS`, default 3). With the setting on, hard (non-emergency) memory pressure parks the most recent chunked-prefill request instead of aborting: it is re-queued without an error, keeps its stream, and resumes in arrival order after enough consecutive ok pressure polls, restoring the blocks that `prefill_progress_commit_blocks` committed (without it the park resumes cold). The oldest admitted request is protected, parked blocks are pinned against eviction until the resume, and the legacy abort remains for emergency pressure, nothing parkable, an exhausted park budget, or external-loop (non-chunked, VLM) and SpecPrefill prefills, which cannot be parked between steps. The scheduler cases run on a small Qwen3.5 hybrid model and compare a resumed request's output with an uninterrupted run; its prompts must stay below the tiny vocabulary of 32 ids, or the embedding read is undefined and the output is nondeterministic. + +Mocked tests do not replace hardware validation: with a real model, run three concurrent long prompts under a ceiling too low for all of them and check that each completes with the park/resume log lines and a cached count close to the last commit, and that no client sees a memory error. diff --git a/omlx/cache/paged_ssd_cache.py b/omlx/cache/paged_ssd_cache.py index e2d7d1aeb7..7904ad5b64 100644 --- a/omlx/cache/paged_ssd_cache.py +++ b/omlx/cache/paged_ssd_cache.py @@ -30,6 +30,7 @@ import time import uuid from collections import OrderedDict +from collections.abc import Iterable from dataclasses import dataclass from pathlib import Path from typing import Any @@ -1774,6 +1775,11 @@ def __init__( # promoted into the raw-byte hot cache. They still consume the same # shared SSD budget as the two main block indexes. self._gdn_sidecar_index = GDNCheckpointIndex(max_size_bytes) + # Block hashes held by parked requests: size enforcement skips them + # (and their GDN sidecars) so a parked prefix survives until resume. + # Refcounted so overlapping prompts can pin the same block. + self._pinned_hashes: dict[bytes, int] = {} + self._pin_lock = threading.Lock() self._hot_cache_only = hot_cache_only self._expected_model_name = expected_model_name self._expected_num_layers = expected_num_layers @@ -4795,6 +4801,33 @@ def _get_effective_max_size(self) -> int: disk_limit = int(disk_available * self._DISK_SAFE_RATIO) return min(self._max_size, disk_limit) + def pin_blocks(self, block_hashes: Iterable[bytes]) -> None: + """Protect blocks (and their GDN sidecars) from size-based eviction.""" + with self._pin_lock: + for block_hash in block_hashes: + key = bytes(block_hash) + self._pinned_hashes[key] = self._pinned_hashes.get(key, 0) + 1 + + def unpin_blocks(self, block_hashes: Iterable[bytes]) -> None: + """Release one pin per hash taken by :meth:`pin_blocks`.""" + with self._pin_lock: + for block_hash in block_hashes: + key = bytes(block_hash) + remaining = self._pinned_hashes.get(key, 0) - 1 + if remaining > 0: + self._pinned_hashes[key] = remaining + else: + self._pinned_hashes.pop(key, None) + + @property + def pinned_block_count(self) -> int: + with self._pin_lock: + return len(self._pinned_hashes) + + def _pinned_snapshot(self) -> frozenset[bytes]: + with self._pin_lock: + return frozenset(self._pinned_hashes) + def _evict_tracked_until_size( self, target_size: int, @@ -4809,14 +4842,29 @@ def _evict_tracked_until_size( avoiding a second, competing budget for GDN history. """ evicted: list[tuple[Any, Any]] = [] + pinned = self._pinned_snapshot() + # Look past pinned entries so one parked prefix never blocks the walk. + depth = 1 + len(pinned) + + def oldest_unpinned(entries: list[Any], hash_attr: str) -> list[Any]: + for entry in entries: + if getattr(entry, hash_attr) not in pinned: + return [entry] + return [] while self._tracked_ssd_size() > target_size: if max_count is not None and len(evicted) >= max_count: break - compatible = self._index.get_lru_entries(1) - incompatible = self._incompatible_index.get_lru_entries(1) - sidecars = self._gdn_sidecar_index.get_lru_entries(1) + compatible = oldest_unpinned( + self._index.get_lru_entries(depth), "block_hash" + ) + incompatible = oldest_unpinned( + self._incompatible_index.get_lru_entries(depth), "block_hash" + ) + sidecars = oldest_unpinned( + self._gdn_sidecar_index.get_lru_entries(depth), "source_block_hash" + ) candidates: list[tuple[float, int, Any, Any]] = [] if compatible: candidates.append((compatible[0].last_access, 0, self._index, compatible[0])) diff --git a/omlx/engine_core.py b/omlx/engine_core.py index b28919e99f..b42c14c06d 100644 --- a/omlx/engine_core.py +++ b/omlx/engine_core.py @@ -851,10 +851,16 @@ async def abort_all_requests( pending_aborts = set( getattr(sched_for_filter, "_pending_abort_ids", None) or () ) + # A parked request holds no live memory: aborting it for memory + # pressure frees nothing and throws away its committed prefix. An + # explicit reason (unload, shutdown) still aborts everything. + is_parked = getattr(sched_for_filter, "is_request_parked", None) request_ids = [ rid for rid in self._output_collectors - if rid not in self._finished_at and rid not in pending_aborts + if rid not in self._finished_at + and rid not in pending_aborts + and not (reason is None and callable(is_parked) and is_parked(rid) is True) ] ceiling = 0 watermark = 0 diff --git a/omlx/request.py b/omlx/request.py index f61053a99b..02f00e2677 100644 --- a/omlx/request.py +++ b/omlx/request.py @@ -244,6 +244,12 @@ def vlm_extra_key_ranges_for_cache( ) packed_prefill_excluded: bool = False # Retries alone after a failed pack + # Memory-pressure park: a prefilling request paused without an error. It + # keeps its client stream and place in line and resumes from its last + # committed prefix. ``parked`` is True from the park until the resume. + parked: bool = False + park_count: int = 0 # Parks taken so far (bounded by max_parks_per_request) + # Request-scoped tool schemas used by protocol output parsers. tools: list[dict[str, Any]] | None = None diff --git a/omlx/scheduler.py b/omlx/scheduler.py index e597c02eea..bc6a9a7be6 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -1351,6 +1351,21 @@ def _is_turboquant_kv_family_cache(cache_obj: Any) -> bool: PREFILL_COMMIT_FINAL_STORE_WAIT_S = 120.0 +# Enforcer polls after a park during which the scheduler still reports "park +# in progress", so the abort waits for the freed memory to return to the OS. +PARK_SETTLE_POLLS = 3 +# A pressure monitor that has not reported for this long is considered gone; +# parked requests then resume instead of waiting for polls that never come. +PARK_SIGNAL_STALE_S = 60.0 + + +class _ParkPins(NamedTuple): + """Block refs and SSD hashes a parked request holds against eviction.""" + + block_ids: list[int] + hashes: list[bytes] + + def _prefill_commit_blocks(config: Any) -> int: """``prefill_progress_commit_blocks`` of a config, 0 when unset or invalid.""" value = getattr(config, "prefill_progress_commit_blocks", 0) @@ -2261,6 +2276,19 @@ def __init__( # PREFILL_COMMIT_FINAL_STORE_WAIT_S. Added on the store worker (GIL-atomic # set.add), consumed by _drain_pending_async_removes on the scheduler thread. self._skipped_final_stores: set[str] = set() + # Memory-pressure park (see request_park_prefill). The flag and the + # poll counters are written by the enforcer thread (GIL-atomic) and + # consumed on the MLX thread. + self._park_requested: bool = False + self._park_settle_polls: int = 0 + self._ok_polls: int = 0 + self._last_pressure_poll_at: float | None = None + self._park_pins: dict[str, _ParkPins] = {} + self._park_stats: dict[str, int] = { + "parks": 0, + "resumes": 0, + "tokens_preserved": 0, + } self.requests: dict[str, Request] = {} # All requests by ID self.finished_req_ids: set[str] = set() # Recently finished self._generation_overflow_recovery_ids: set[str] = set() @@ -5611,6 +5639,10 @@ def get_active_hot_cache_block_hashes(self) -> set[bytes]: continue if block_hash is not None: hashes.add(bytes(block_hash)) + # Parked requests hold no live table, but their pinned prefix must + # survive a hot-cache shrink too. + for pins in list(self._park_pins.values()): + hashes.update(pins.hashes) return hashes def _clear_memory_admission_blocker(self, request_id: str | None = None) -> None: @@ -5696,6 +5728,11 @@ def _memory_admission_stall_output(self, reason: str) -> RequestOutput | None: request = self.waiting[0] request_id = request.request_id + if request.parked: + # Parked on purpose: it waits as long as pressure lasts; the + # client's own timeouts apply. + self._clear_memory_admission_blocker(request_id) + return None now = time.monotonic() if request_id != self._memory_admission_blocked_request_id: self._memory_admission_blocked_request_id = request_id @@ -5761,6 +5798,9 @@ def _store_cache_admission_stall_output( request = self.waiting[0] request_id = request.request_id + if request.parked: + self._clear_store_cache_admission_blocker(request_id) + return None now = time.monotonic() if request_id != self._store_cache_admission_blocked_request_id: self._store_cache_admission_blocked_request_id = request_id @@ -10654,6 +10694,9 @@ def _retry_prefills_cold_after_oom(self, request: Request) -> bool: otherwise be attached here; a client re-issue still resumes from them. Gated on the setting so the default behavior is unchanged. """ + if getattr(request, "parked", False): + # A parked request resumes from its committed blocks by design. + return False retries = getattr(request, "prefill_oom_retries", 0) return ( isinstance(retries, int) @@ -11798,6 +11841,236 @@ def _cleanup_prefill_abort_request( self._pending_abort_ids.discard(request.request_id) self._do_abort_request(request.request_id) + # ------------------------------------------------------------------ + # Memory-pressure park: pause a prefilling request instead of aborting. + # ------------------------------------------------------------------ + + def _park_enabled(self) -> bool: + return getattr(self.config, "memory_pressure_park", False) is True + + def note_pressure_poll(self, level: str) -> None: + """Record one enforcer poll (thread-safe; counters only). + + Parked requests resume after ``park_resume_ok_polls`` consecutive + ``ok`` polls (hysteresis against flapping at the watermark). + """ + self._last_pressure_poll_at = time.monotonic() + if level == "ok": + self._ok_polls += 1 + self._park_settle_polls = 0 + else: + self._ok_polls = 0 + + def _park_resume_allowed(self) -> bool: + """True once enough consecutive ok polls were seen (or no monitor runs).""" + seen = self._last_pressure_poll_at + if seen is None or time.monotonic() - seen > PARK_SIGNAL_STALE_S: + return True # no live pressure monitor: never starve a parked request + need = getattr(self.config, "park_resume_ok_polls", 3) + return self._ok_polls >= max(1, need) + + def is_request_parked(self, request_id: str) -> bool: + """Whether the request is currently parked (holds no live memory).""" + request = self.requests.get(request_id) + return bool(request is not None and request.parked) + + def get_park_stats(self) -> dict[str, int]: + """Counters for the diagnostics/admin stats.""" + stats = dict(self._park_stats) + stats["parked_now"] = sum(1 for r in list(self.waiting) if r.parked) + stats["pinned_requests"] = len(self._park_pins) + return stats + + def _parkable_prefills(self) -> list[Request]: + """Chunked prefills that can be parked safely. + + Only requests in the chunked-prefill loop qualify: their state lives + between steps. External-loop prefills (non-chunked, VLM) run to + completion inside one ``_schedule_waiting`` call and are never + between steps; VLM embeds and SpecPrefill patch model-wide state, so + they are excluded as well. + """ + budget = getattr(self.config, "max_parks_per_request", 3) + return [ + request + for request in list(self.prefilling) + if request.request_id in self._prefill_states + and request.park_count < budget + and request.specprefill_indices is None + and request.vlm_inputs_embeds is None + ] + + def _select_park_victim(self) -> Request | None: + """Most recent arrival first; the oldest admitted request is protected. + + The oldest request among everything admitted (prefilling or decoding) + is skipped while any other prefill is parkable. It is only parked + when it is the sole candidate, which still helps when the pressure + comes from outside this process. + """ + candidates = self._parkable_prefills() + if not candidates: + return None + admitted = list(self.prefilling) + list(self.running.values()) + oldest = min(admitted, key=lambda r: (r.arrival_time, r.request_id)) + candidates.sort(key=lambda r: (r.arrival_time, r.request_id), reverse=True) + for request in candidates: + if request.request_id != oldest.request_id: + return request + return candidates[0] + + def request_park_prefill(self) -> bool: + """Ask for a prefill victim to be parked (thread-safe, flag only). + + Called by ProcessMemoryEnforcer on the asyncio thread at hard + pressure. Returns True when a victim is parkable, a park is pending, + or one just ran and its memory is still returning; the enforcer then + defers its abort. False (park disabled, nothing parkable, budget + spent) leaves the legacy abort in place. + """ + if not self._park_enabled(): + return False + if self._park_requested: + return True + try: + victim = self._select_park_victim() + except RuntimeError: # queue mutated mid-read on the MLX thread + victim = True + if victim is not None: + self._park_requested = True + return True + if self._park_settle_polls > 0: + self._park_settle_polls -= 1 + return True + return False + + def _process_pending_park(self) -> bool: + """Park one victim if the enforcer asked (MLX thread, step start).""" + if not self._park_requested: + return False + self._park_requested = False + if not self._park_enabled(): + return False + victim = self._select_park_victim() + if victim is None: + return False + self._park_prefill(victim, reason="hard memory pressure") + self._park_settle_polls = PARK_SETTLE_POLLS + return True + + def _park_prefill(self, request: Request, reason: str) -> None: + """Pause a chunked prefill without an error and without blocking. + + The request keeps its client stream, prompt, sampling params and + arrival time. Its live cache is dropped; blocks an incremental commit + stored stay in the prefix cache, pinned against eviction, and the + re-admission does a fresh prefix lookup that restores them. Teardown + steps run behind any in-flight commit through ``_after_commit``. + """ + rid = request.request_id + table = ( + self.paged_cache_manager.get_block_table(rid) + if self.paged_cache_manager is not None + else None + ) + committed = table.num_tokens if table else 0 + self._prefill_states.pop(rid, None) + self.prefilling = deque(r for r in self.prefilling if r.request_id != rid) + self._reset_request_for_reprefill(request) + request.parked = True + request.park_count += 1 + self._clear_request_admission_bookkeeping(rid) + get_prefill_tracker().remove(rid) + # Order matters: pin first, then release the table's own refs. + self._after_commit(rid, lambda: self._pin_parked_blocks(rid)) + self._release_paged_cache_for_request(rid) + self._drop_boundary_snapshots_for_request(rid) + self._enqueue_parked(request) + self._ok_polls = 0 + self._park_stats["parks"] += 1 + Scheduler._clear_cache(self) + budget = getattr(self.config, "max_parks_per_request", 3) + logger.info( + "Parked request %s at %d tokens committed (park %d/%d), reason: %s%s", + rid, + committed, + request.park_count, + budget, + reason, + ( + "" + if _prefill_commit_blocks(self.config) > 0 + else " (prefill_progress_commit_blocks is off: it will resume cold)" + ), + ) + + def _enqueue_parked(self, request: Request) -> None: + """Queue a parked request in arrival order, ahead of unparked ones.""" + key = (request.arrival_time, request.request_id) + index = 0 + for queued in self.waiting: + if queued.parked and (queued.arrival_time, queued.request_id) <= key: + index += 1 + else: + break + self.waiting.insert(index, request) + + def _pin_parked_blocks(self, request_id: str) -> None: + """Hold the committed blocks of a parked request against eviction. + + Takes one extra block ref per committed block (so the table's own + release leaves them referenced) and pins their hashes in the SSD + index, whose size enforcement skips them. Skipped when the request + was aborted or already resumed before this deferred step ran. + """ + request = self.requests.get(request_id) + manager = self.paged_cache_manager + if request is None or not request.parked or manager is None: + return + table = manager.get_block_table(request_id) + if not table or not table.block_ids: + return + self._unpin_parked(request_id) + block_ids: list[int] = [] + hashes: list[bytes] = [] + for block_id in table.block_ids: + if not manager.increment_ref(block_id): + continue + block_ids.append(block_id) + block = manager.allocated_blocks.get(block_id) + block_hash = getattr(block, "block_hash", None) + if block_hash is not None: + hashes.append(bytes(block_hash)) + if not block_ids: + return + self._park_pins[request_id] = _ParkPins(block_ids, hashes) + ssd = self.paged_ssd_cache_manager + if ssd is not None and hasattr(ssd, "pin_blocks"): + ssd.pin_blocks(hashes) + + def _unpin_parked(self, request_id: str) -> None: + pins = self._park_pins.pop(request_id, None) + if pins is None: + return + if self.paged_cache_manager is not None: + self.paged_cache_manager.release_for_eviction(pins.block_ids) + ssd = self.paged_ssd_cache_manager + if ssd is not None and hasattr(ssd, "unpin_blocks"): + ssd.unpin_blocks(pins.hashes) + + def _finish_park_resume(self, request: Request) -> None: + """Re-admission of a parked request: its fresh lookup holds the blocks.""" + self._unpin_parked(request.request_id) + request.parked = False + self._park_settle_polls = 0 + self._park_stats["resumes"] += 1 + self._park_stats["tokens_preserved"] += request.cached_tokens or 0 + logger.info( + "Resumed parked request %s: cached=%d", + request.request_id, + request.cached_tokens or 0, + ) + def request_idle_reclaim(self) -> None: """Enqueue a between-turn Metal reclaim (thread-safe, no Metal touch). @@ -11909,6 +12182,7 @@ def _do_abort_request(self, request_id: str) -> bool: return False self._clear_request_admission_bookkeeping(request_id) + self._unpin_parked(request_id) # Remove from waiting queue if request.status == RequestStatus.WAITING: @@ -12040,6 +12314,7 @@ def has_requests(self) -> bool: or self._deferred_clear_at is not None or self._pending_reclaim_request or self._pending_pressure_clear + or self._park_requested ) def has_pending_route_preflight_cleanup(self) -> bool: @@ -12752,6 +13027,12 @@ def _schedule_waiting_scan( # crosses soft_threshold. New prefills wait; in-flight requests # continue. First request always passes (no admitted work yet) # so admission can recover by completing the current generation. + # Parked requests sit at the front in arrival order and resume + # only after enough consecutive ok pressure polls; nothing newer + # overtakes them while they wait. + if self.waiting[0].parked and not self._park_resume_allowed(): + break + admitted = self._num_admitted_requests() if self._admission_paused and admitted: logger.debug( @@ -12884,6 +13165,8 @@ def _schedule_waiting_scan( # #2183/#2197 chunk-view and #2235 batch-KV-mutation fixes. with mx.stream(self._stream): self._prepare_prefix_cache_for_request(request) + if request.parked: + self._finish_park_resume(request) # Determine tokens to process and cache to use # Note: Don't use `remaining_tokens or prompt_token_ids` because empty list @@ -14899,6 +15182,11 @@ def step(self) -> SchedulerOutput: if drained_async_removes: output.has_work = True + # Park a prefill victim requested by the memory enforcer. Runs before + # any chunk so a parked request never has a forward in flight. + if self._process_pending_park(): + output.has_work = True + # Check memory pressure and evict if needed (tiered cache) if self.memory_monitor is not None: self._check_memory_pressure() @@ -15204,6 +15492,8 @@ def get_stats(self) -> dict[str, Any]: # Include cache stats if self.block_aware_cache is not None: stats["ssd_cache"] = self.block_aware_cache.get_stats() + if getattr(self.config, "memory_pressure_park", False) is True: + stats["park"] = self.get_park_stats() return stats def get_cache_stats(self) -> dict[str, Any] | None: @@ -15276,6 +15566,10 @@ def reset(self) -> None: self._deferred_teardown_since.clear() self._stuck_teardown_logged.clear() self._skipped_final_stores.clear() + for parked_id in list(self._park_pins): + self._unpin_parked(parked_id) + self._park_requested = False + self._park_settle_polls = 0 self._prefill_commits.clear() self._cache_freshness_waits.clear() self._prefix_cache_prepared.clear() @@ -15429,6 +15723,8 @@ def shutdown(self) -> None: # no step-thread caller to wake here. Inflight futures are drained # below before the executor is asked to shut down. commit_store_busy = self._shutdown_prefill_commits() + for parked_id in list(self._park_pins): + self._unpin_parked(parked_id) # Wait for any inflight async store_cache futures + drain pending # batch_generator removes so the writer thread / underlying paged SSD # cache see all blocks before close(). diff --git a/tests/test_engine_core.py b/tests/test_engine_core.py index f5f2b1165f..60df9862f6 100644 --- a/tests/test_engine_core.py +++ b/tests/test_engine_core.py @@ -1280,6 +1280,31 @@ async def test_abort_all_requests_skips_requests_already_aborted( await engine.stop() engine.close() + @pytest.mark.asyncio + async def test_abort_all_requests_leaves_parked_requests_alone( + self, mock_model, mock_tokenizer + ): + """A parked request holds no memory; a pressure abort must keep it.""" + with patch("omlx.engine_core.get_registry") as mock_registry: + mock_registry.return_value.acquire.return_value = True + engine = EngineCore(model=mock_model, tokenizer=mock_tokenizer) + try: + await engine.start() + engine.scheduler.has_requests = lambda: False + parked_id = await engine.add_request(prompt="Hello") + live_id = await engine.add_request(prompt="World") + engine.scheduler.requests[parked_id].parked = True + + assert await engine.abort_all_requests() == 1 + assert engine._output_collectors[parked_id].get_nowait() is None + assert engine._output_collectors[live_id].get_nowait().finished + + # An explicit reason (manual unload, shutdown) aborts it too. + assert await engine.abort_all_requests(reason="unloading") == 1 + finally: + await engine.stop() + engine.close() + @pytest.mark.asyncio async def test_abort_all_requests_uses_explicit_unload_reason( self, mock_model, mock_tokenizer diff --git a/tests/test_scheduler_park.py b/tests/test_scheduler_park.py new file mode 100644 index 0000000000..763cc76599 --- /dev/null +++ b/tests/test_scheduler_park.py @@ -0,0 +1,585 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Park-instead-of-abort for chunked prefill under memory pressure. + +The tests drive the real scheduler step loop on a small initialized Qwen3.5 +hybrid model against real paged-SSD, boundary-snapshot and prefix stores. A +parked request keeps its client stream and its place in line, drops its live +cache, and resumes from the blocks an incremental commit stored. +""" + +import time +from types import SimpleNamespace + +import test_scheduler_prefill_progress_commit as commit_rig +from test_scheduler_prefill_progress_commit import BLOCK, _returns_promptly, _Rig + +from omlx.request import Request, RequestStatus, SamplingParams + +# Controllable commit worker fixture shared with the incremental-commit suite. +gated = commit_rig.gated + + +def _prompt(seed): + """24 tokens (23 prefill tokens: five full blocks plus a tail). + + Token ids stay below the tiny model's vocabulary of 32; an out-of-range id + reads undefined embedding memory and makes the output nondeterministic. + """ + return [3 + (seed * 5 + i * 7) % 28 for i in range(24)] + + +PROMPT_A = _prompt(1) +PROMPT_B = _prompt(2) +PROMPT_C = _prompt(3) +PROMPT_D = _prompt(4) + + +def make_rig(tmp_path, tokenizer, *, park=True, max_parks=3, ok_polls=3, commit=1): + rig = _Rig( + tmp_path, + tokenizer, + split=False, + commit_blocks=commit, + memory_pressure_park=park, + max_parks_per_request=max_parks, + park_resume_ok_polls=ok_polls, + ) + # The pressure monitor is "live": the hold gate waits for ok polls. + rig.scheduler.note_pressure_poll("soft") + return rig + + +def submit(rig, request_id, tokens, arrival, max_tokens=3): + request = Request( + request_id=request_id, + prompt=list(tokens), + sampling_params=SamplingParams(max_tokens=max_tokens, temperature=0), + arrival_time=arrival, + ) + rig.scheduler.add_request(request) + return request + + +def step(rig, n=1): + """Step the scheduler, settling commit workers so cadence is deterministic.""" + outputs = [] + for _ in range(n): + result = rig.scheduler.step() + outputs.extend(result.outputs) + rig.drain() + return outputs + + +def prefilling_ids(rig): + return [r.request_id for r in rig.scheduler.prefilling] + + +def waiting_ids(rig): + return [r.request_id for r in rig.scheduler.waiting] + + +def step_until(rig, predicate, limit=60): + outputs = [] + for _ in range(limit): + if predicate(): + return outputs + outputs.extend(step(rig)) + raise AssertionError("condition not reached") + + +def prefill_two(rig): + """Old (A) and young (B) both mid-prefill with committed blocks.""" + old = submit(rig, "old", PROMPT_A, arrival=1.0) + young = submit(rig, "young", PROMPT_B, arrival=2.0) + step_until( + rig, + lambda: set(prefilling_ids(rig)) == {"old", "young"} + and rig.table_tokens("young") >= BLOCK, + ) + return old, young + + +def run_to_completion(rig, requests, limit=200): + outputs = [] + for _ in range(limit): + if all( + r.is_finished() or r.request_id not in rig.scheduler.requests + for r in requests + ): + break + outputs.extend(step(rig)) + for future in list(rig.scheduler._inflight_store_futures.values()): + future.result(timeout=30) + rig.scheduler._drain_pending_async_removes() + return outputs + + +def finish_ok_polls(rig, n): + for _ in range(n): + rig.scheduler.note_pressure_poll("ok") + + +# --- Request side of the enforcer contract ---------------------------------- + + +def test_park_disabled_never_accepts_a_park_request(tmp_path, mock_tokenizer): + rig = make_rig(tmp_path, mock_tokenizer, park=False) + try: + prefill_two(rig) + assert rig.scheduler.request_park_prefill() is False + step(rig) + assert set(prefilling_ids(rig)) == {"old", "young"} + finally: + rig.close() + + +def test_nothing_parkable_is_reported_so_the_enforcer_aborts(tmp_path, mock_tokenizer): + rig = make_rig(tmp_path, mock_tokenizer) + try: + assert rig.scheduler.request_park_prefill() is False # nothing admitted + request = submit(rig, "only", PROMPT_A, arrival=1.0) + # Still waiting (not prefilling): not parkable. + assert rig.scheduler.request_park_prefill() is False + assert not request.parked + finally: + rig.close() + + +def test_a_request_that_cannot_be_parked_safely_is_not_a_victim( + tmp_path, mock_tokenizer +): + """VLM and SpecPrefill prefills run outside the chunked loop or patch the + whole model; they are never victims.""" + rig = make_rig(tmp_path, mock_tokenizer) + try: + old, young = prefill_two(rig) + young.vlm_inputs_embeds = object() + old.specprefill_indices = [0] + assert rig.scheduler.request_park_prefill() is False + finally: + rig.close() + + +# --- Victim policy ------------------------------------------------------------ + + +def test_hard_pressure_parks_the_youngest_prefill_without_an_error( + tmp_path, mock_tokenizer +): + rig = make_rig(tmp_path, mock_tokenizer) + try: + old, young = prefill_two(rig) + scheduler = rig.scheduler + assert scheduler.request_park_prefill() is True + outputs = step(rig) + + assert not [o for o in outputs if o.finished or o.error] + assert prefilling_ids(rig) == ["old"] # the oldest keeps running + assert waiting_ids(rig) == ["young"] + assert young.parked and young.park_count == 1 + assert young.status == RequestStatus.WAITING + assert "young" in scheduler.requests # the client stream stays open + assert "young" not in scheduler._prefill_states + assert young.prompt_cache is None + assert young.arrival_time == 2.0 + assert young.prompt_token_ids == PROMPT_B + finally: + rig.close() + + +def test_the_oldest_is_protected_while_a_younger_prefill_is_parkable( + tmp_path, mock_tokenizer +): + rig = make_rig(tmp_path, mock_tokenizer) + try: + prefill_two(rig) + rig.scheduler.request_park_prefill() + step(rig) + # The younger one was parked; the oldest keeps prefilling. + assert waiting_ids(rig) == ["young"] + assert rig.scheduler.requests["old"].park_count == 0 + finally: + rig.close() + + +def test_a_sole_prefill_is_parkable_when_pressure_comes_from_elsewhere( + tmp_path, mock_tokenizer +): + rig = make_rig(tmp_path, mock_tokenizer) + try: + only = submit(rig, "only", PROMPT_A, arrival=1.0) + step_until(rig, lambda: prefilling_ids(rig) == ["only"]) + assert rig.scheduler.request_park_prefill() is True + step(rig) + assert only.parked and waiting_ids(rig) == ["only"] + finally: + rig.close() + + +def test_one_victim_is_parked_per_step_and_per_request(tmp_path, mock_tokenizer): + rig = make_rig(tmp_path, mock_tokenizer) + try: + submit(rig, "r1", PROMPT_A, arrival=1.0) + submit(rig, "r2", PROMPT_B, arrival=2.0) + submit(rig, "r3", PROMPT_C, arrival=3.0) + step_until(rig, lambda: len(prefilling_ids(rig)) == 3) + rig.scheduler.request_park_prefill() + step(rig) + assert waiting_ids(rig) == ["r3"] # one victim only + assert set(prefilling_ids(rig)) == {"r1", "r2"} + finally: + rig.close() + + +def test_parked_requests_resume_in_arrival_order_ahead_of_newer_ones( + tmp_path, mock_tokenizer +): + rig = make_rig(tmp_path, mock_tokenizer) + try: + submit(rig, "r1", PROMPT_A, arrival=1.0) + submit(rig, "r2", PROMPT_B, arrival=2.0) + submit(rig, "r3", PROMPT_C, arrival=3.0) + step_until(rig, lambda: len(prefilling_ids(rig)) == 3) + # A newer, never-admitted request is already queued. + submit(rig, "r4", PROMPT_D, arrival=4.0) + rig.scheduler.request_park_prefill() + step(rig) # parks r3 + rig.scheduler.request_park_prefill() + step(rig) # parks r2 (r1 protected) + assert waiting_ids(rig) == ["r2", "r3", "r4"] + finally: + rig.close() + + +# --- Hold gate ---------------------------------------------------------------- + + +def test_no_resume_before_the_required_consecutive_ok_polls(tmp_path, mock_tokenizer): + rig = make_rig(tmp_path, mock_tokenizer, ok_polls=3) + try: + old, young = prefill_two(rig) + rig.scheduler.request_park_prefill() + step(rig) + assert waiting_ids(rig) == ["young"] + + finish_ok_polls(rig, 2) + step(rig, 3) + assert waiting_ids(rig) == ["young"] # two ok polls are not enough + + rig.scheduler.note_pressure_poll("soft") # the streak is broken + finish_ok_polls(rig, 2) + step(rig, 3) + assert waiting_ids(rig) == ["young"] + + finish_ok_polls(rig, 1) # third consecutive ok poll + step_until( + rig, lambda: "young" in prefilling_ids(rig) or young.output_token_ids + ) + assert not young.parked + finally: + rig.close() + + +def test_new_requests_do_not_overtake_a_parked_one(tmp_path, mock_tokenizer): + rig = make_rig(tmp_path, mock_tokenizer) + try: + prefill_two(rig) + rig.scheduler.request_park_prefill() + step(rig) + submit(rig, "newer", PROMPT_C, arrival=9.0) + step(rig, 4) + assert waiting_ids(rig) == ["young", "newer"] + assert "newer" not in prefilling_ids(rig) + finally: + rig.close() + + +def test_parked_request_is_exempt_from_the_admission_stall_timeout( + tmp_path, mock_tokenizer +): + rig = make_rig(tmp_path, mock_tokenizer) + try: + scheduler = rig.scheduler + scheduler._MEMORY_ADMISSION_STALL_TIMEOUT_S = 0.0 + scheduler._STORE_CACHE_ADMISSION_STALL_TIMEOUT_S = 0.0 + old, young = prefill_two(rig) + scheduler.request_park_prefill() + step(rig) + scheduler._admission_paused = True + for _ in range(3): + assert scheduler._memory_admission_stall_output("admission_paused") is None + time.sleep(0.01) + outputs = step(rig, 5) + assert not [o for o in outputs if o.error] + assert waiting_ids(rig) == ["young"] + assert "young" in scheduler.requests + finally: + rig.close() + + +def test_the_resume_signal_is_not_awaited_when_no_monitor_reports( + tmp_path, mock_tokenizer +): + """Without an enforcer (no poll ever seen) a parked request is not starved.""" + rig = _Rig( + tmp_path, + mock_tokenizer, + split=False, + commit_blocks=1, + memory_pressure_park=True, + ) + try: + assert rig.scheduler._park_resume_allowed() is True + rig.scheduler.note_pressure_poll("hard") + assert rig.scheduler._park_resume_allowed() is False + finally: + rig.close() + + +# --- Resume ------------------------------------------------------------------ + + +def uninterrupted_output(tmp_path, tokenizer): + rig = make_rig(tmp_path / "baseline", tokenizer, park=False) + try: + request = submit(rig, "young", PROMPT_B, arrival=2.0) + run_to_completion(rig, [request]) + return list(request.output_token_ids) + finally: + rig.close() + + +def test_resume_restores_the_committed_boundary_and_matches_an_uninterrupted_run( + tmp_path, mock_tokenizer, caplog +): + import logging + + expected = uninterrupted_output(tmp_path, mock_tokenizer) + assert expected + + rig = make_rig(tmp_path / "park", mock_tokenizer) + try: + old, young = prefill_two(rig) + scheduler = rig.scheduler + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + scheduler.request_park_prefill() + step(rig) + rig.drain() + committed = rig.probe(PROMPT_B)[0].num_tokens + assert committed >= BLOCK + assert any( + "Parked request young" in r.getMessage() + and "park 1/3" in r.getMessage() + for r in caplog.records + ) + + finish_ok_polls(rig, 3) + step_until(rig, lambda: "young" in prefilling_ids(rig)) + assert young.cached_tokens == committed + assert any( + f"Resumed parked request young: cached={committed}" in r.getMessage() + for r in caplog.records + ) + outputs = run_to_completion(rig, [old, young]) + assert not [o for o in outputs if o.error] + assert list(young.output_token_ids) == expected + assert young.park_count == 1 and not young.parked + stats = scheduler.get_park_stats() + assert stats["parks"] == 1 and stats["resumes"] == 1 + finally: + rig.close() + + +def test_the_cold_retry_guard_is_bypassed_for_a_parked_request( + tmp_path, mock_tokenizer +): + rig = make_rig(tmp_path, mock_tokenizer) + try: + old, young = prefill_two(rig) + young.prefill_oom_retries = 1 # an earlier internal SDPA-OOM requeue + assert rig.scheduler._retry_prefills_cold_after_oom(young) is True + young.parked = True + assert rig.scheduler._retry_prefills_cold_after_oom(young) is False + finally: + rig.close() + + +def test_park_budget_exhaustion_falls_back_to_the_abort(tmp_path, mock_tokenizer): + rig = make_rig(tmp_path, mock_tokenizer, max_parks=1, ok_polls=1) + try: + only = submit(rig, "only", PROMPT_A, arrival=1.0) + step_until(rig, lambda: prefilling_ids(rig) == ["only"]) + assert rig.scheduler.request_park_prefill() is True + step(rig) + finish_ok_polls(rig, 1) + step_until(rig, lambda: "only" in prefilling_ids(rig)) + assert only.park_count == 1 + # The one allowed park is spent: the enforcer is told to abort. + assert rig.scheduler.request_park_prefill() is False + finally: + rig.close() + + +def test_settling_after_a_park_defers_the_abort_for_a_few_polls( + tmp_path, mock_tokenizer +): + rig = make_rig(tmp_path, mock_tokenizer, max_parks=1) + try: + submit(rig, "only", PROMPT_A, arrival=1.0) + step_until(rig, lambda: prefilling_ids(rig) == ["only"]) + rig.scheduler.request_park_prefill() + step(rig) + # Memory is returning to the OS; the enforcer must not abort yet. + answers = [rig.scheduler.request_park_prefill() for _ in range(6)] + assert answers[0] is True + assert answers[-1] is False + finally: + rig.close() + + +# --- Eviction safety (pinning) -------------------------------------------------- + + +def test_committed_blocks_are_pinned_while_parked_and_released_after_resume( + tmp_path, mock_tokenizer +): + rig = make_rig(tmp_path, mock_tokenizer, ok_polls=1) + try: + old, young = prefill_two(rig) + scheduler = rig.scheduler + scheduler.request_park_prefill() + step(rig) + rig.drain() + + pins = scheduler._park_pins["young"] + assert pins.block_ids and pins.hashes + assert rig.ssd.pinned_block_count == len(pins.hashes) + for block_id in pins.block_ids: + assert rig.paged.allocated_blocks[block_id].ref_count >= 1 + + # Even an unbounded size enforcement keeps the parked prefix on disk. + rig.ssd._evict_tracked_until_size(0) + table, remaining = rig.probe(PROMPT_B) + assert table is not None and table.num_tokens >= BLOCK + assert scheduler.get_active_hot_cache_block_hashes() >= set(pins.hashes) + + finish_ok_polls(rig, 1) + step_until(rig, lambda: "young" in prefilling_ids(rig)) + assert "young" not in scheduler._park_pins + assert rig.ssd.pinned_block_count == 0 + finally: + rig.close() + + +def test_pins_are_released_when_a_parked_request_is_aborted(tmp_path, mock_tokenizer): + rig = make_rig(tmp_path, mock_tokenizer) + try: + prefill_two(rig) + scheduler = rig.scheduler + scheduler.request_park_prefill() + step(rig) + rig.drain() + assert "young" in scheduler._park_pins + + assert scheduler.abort_request("young") + step(rig, 2) + assert "young" not in scheduler._park_pins + assert rig.ssd.pinned_block_count == 0 + assert "young" not in scheduler.requests + assert "young" not in waiting_ids(rig) + finally: + rig.close() + + +def test_pinned_blocks_are_not_evicted_from_the_ssd_index_by_lru( + tmp_path, mock_tokenizer +): + rig = make_rig(tmp_path, mock_tokenizer) + try: + old, young = prefill_two(rig) + rig.drain() + table, _ = rig.probe(PROMPT_B) + assert table is not None + hashes = [ + bytes(rig.paged.allocated_blocks[b].block_hash) for b in table.block_ids + ] + rig.ssd.pin_blocks(hashes) + rig.ssd._evict_tracked_until_size(0) + for block_hash in hashes: + assert rig.ssd._index.get(block_hash) is not None + rig.ssd.unpin_blocks(hashes) + rig.ssd._evict_tracked_until_size(0) + assert all(rig.ssd._index.get(h) is None for h in hashes) + assert rig.ssd.pinned_block_count == 0 + finally: + rig.close() + + +# --- Teardown never blocks the MLX thread ------------------------------------------ + + +def test_park_with_a_commit_in_flight_defers_the_teardown_without_blocking( + tmp_path, mock_tokenizer, gated +): + rig = make_rig(tmp_path, mock_tokenizer, ok_polls=1) + gate = None + try: + scheduler = rig.scheduler + old, young = prefill_two(rig) # commits ran before the gate was armed + gate = gated(rig) + # Run until the young request has a commit that cannot finish. + for _ in range(8): + if "young" in scheduler._prefill_commits: + break + scheduler.step() + assert "young" in scheduler._prefill_commits + assert not scheduler._prefill_commits["young"][0].done() + scheduler.request_park_prefill() + + assert _returns_promptly(scheduler._process_pending_park) + assert young.parked and waiting_ids(rig)[0] == "young" + assert scheduler._teardown_pending("young") # waits behind the commit + + # A held head is set aside; it is not admitted while its teardown pends. + finish_ok_polls(rig, 1) + scheduler.step() + assert "young" not in prefilling_ids(rig) + + gate.release.set() + rig.drain() + assert not scheduler._teardown_pending("young") + assert "young" in scheduler._park_pins + finally: + if gate is not None: + gate.release.set() + rig.close() + + +def test_reset_and_shutdown_release_every_pin(tmp_path, mock_tokenizer): + rig = make_rig(tmp_path, mock_tokenizer) + try: + prefill_two(rig) + rig.scheduler.request_park_prefill() + step(rig) + rig.drain() + assert rig.ssd.pinned_block_count > 0 + rig.scheduler.reset() + assert not rig.scheduler._park_pins + assert rig.ssd.pinned_block_count == 0 + finally: + rig.close() + + +# --- Engine bulk abort ------------------------------------------------------------- + + +def test_is_request_parked_reads_the_request_flag(): + """EngineCore.abort_all_requests uses it to spare parked requests.""" + from omlx.scheduler import Scheduler + + scheduler = SimpleNamespace( + requests={"p": SimpleNamespace(parked=True), "l": SimpleNamespace(parked=False)} + ) + assert Scheduler.is_request_parked(scheduler, "p") is True + assert Scheduler.is_request_parked(scheduler, "l") is False + assert Scheduler.is_request_parked(scheduler, "missing") is False diff --git a/tests/test_scheduler_prefill_progress_commit.py b/tests/test_scheduler_prefill_progress_commit.py index 2bf88a5dc6..5c23e10592 100644 --- a/tests/test_scheduler_prefill_progress_commit.py +++ b/tests/test_scheduler_prefill_progress_commit.py @@ -52,7 +52,16 @@ def _tiny_hybrid_model(): class _Rig: """A scheduler wired to real stores, plus helpers to drive prefill.""" - def __init__(self, tmp_path, tokenizer, *, split, commit_blocks, tq_bits=None): + def __init__( + self, + tmp_path, + tokenizer, + *, + split, + commit_blocks, + tq_bits=None, + **config_overrides, + ): mx.random.seed(11) self.model = _tiny_hybrid_model() self.scheduler = Scheduler( @@ -64,6 +73,7 @@ def __init__(self, tmp_path, tokenizer, *, split, commit_blocks, tq_bits=None): chunked_prefill=True, prefill_step_size=BLOCK, prefill_progress_commit_blocks=commit_blocks, + **config_overrides, ), ) self.paged = PagedCacheManager( From 3c459e2ddc6202eb55979631a0c1e63ea8d0d709 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Thu, 1 Oct 2026 15:48:38 -0600 Subject: [PATCH 10/18] fix(engine): spare parked requests only when the caller keeps the model 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. --- omlx/engine/batched.py | 2 + omlx/engine/vlm.py | 2 + omlx/engine_core.py | 18 ++++- omlx/process_memory_enforcer.py | 35 +++++++- tests/test_engine_core.py | 41 ++++++++-- tests/test_process_memory_enforcer.py | 112 ++++++++++++++++++++++++++ 6 files changed, 198 insertions(+), 12 deletions(-) diff --git a/omlx/engine/batched.py b/omlx/engine/batched.py index 4ca34435a1..aaef48d678 100644 --- a/omlx/engine/batched.py +++ b/omlx/engine/batched.py @@ -1578,11 +1578,13 @@ async def abort_all_requests( *, reason: str | None = None, error_code: str | None = None, + spare_parked: bool = False, ) -> int: """Abort all active requests without stopping the engine.""" if self._engine and self._engine.engine: return await self._engine.engine.abort_all_requests( reason=reason, error_code=error_code, + spare_parked=spare_parked, ) return 0 diff --git a/omlx/engine/vlm.py b/omlx/engine/vlm.py index c537e4df2d..0c1d3e84ad 100644 --- a/omlx/engine/vlm.py +++ b/omlx/engine/vlm.py @@ -6024,6 +6024,7 @@ async def abort_all_requests( *, reason: str | None = None, error_code: str | None = None, + spare_parked: bool = False, ) -> int: """Abort all active requests.""" if self.is_diffusion_model: @@ -6035,5 +6036,6 @@ async def abort_all_requests( return await self._engine.engine.abort_all_requests( reason=reason, error_code=error_code, + spare_parked=spare_parked, ) return 0 diff --git a/omlx/engine_core.py b/omlx/engine_core.py index b42c14c06d..ff18d94479 100644 --- a/omlx/engine_core.py +++ b/omlx/engine_core.py @@ -827,6 +827,7 @@ async def abort_all_requests( *, reason: str | None = None, error_code: str | None = None, + spare_parked: bool = False, ) -> int: """Abort all active requests without stopping the engine. @@ -834,6 +835,12 @@ async def abort_all_requests( for deferred abort in the scheduler. Cleanup is handled by the consumer (stream_outputs/generate). Without an explicit reason, preserve the memory-pressure error used by the process enforcer. + + Parked requests (memory-pressure park) are aborted too unless the + caller passes ``spare_parked=True``. Only a caller that keeps the + model loaded and lets the scheduler resume them may spare them; + every unload, eviction, emergency or shutdown path must abort them, + or they are orphaned (or block the unload from ever draining). """ from .utils.proc_memory import get_phys_footprint @@ -852,15 +859,15 @@ async def abort_all_requests( getattr(sched_for_filter, "_pending_abort_ids", None) or () ) # A parked request holds no live memory: aborting it for memory - # pressure frees nothing and throws away its committed prefix. An - # explicit reason (unload, shutdown) still aborts everything. + # pressure frees nothing and throws away its committed prefix. Only + # an explicit ``spare_parked`` keeps it (keep-loaded hard path). is_parked = getattr(sched_for_filter, "is_request_parked", None) request_ids = [ rid for rid in self._output_collectors if rid not in self._finished_at and rid not in pending_aborts - and not (reason is None and callable(is_parked) and is_parked(rid) is True) + and not (spare_parked and callable(is_parked) and is_parked(rid) is True) ] ceiling = 0 watermark = 0 @@ -1480,12 +1487,15 @@ async def abort_all_requests( *, reason: str | None = None, error_code: str | None = None, + spare_parked: bool = False, ) -> int: """Abort all active requests without stopping the engine.""" engine = getattr(self, "engine", None) if engine is None: return 0 - return await engine.abort_all_requests(reason=reason, error_code=error_code) + return await engine.abort_all_requests( + reason=reason, error_code=error_code, spare_parked=spare_parked + ) async def stream_outputs( self, diff --git a/omlx/process_memory_enforcer.py b/omlx/process_memory_enforcer.py index b0e9448d21..32ecf83c61 100644 --- a/omlx/process_memory_enforcer.py +++ b/omlx/process_memory_enforcer.py @@ -1571,6 +1571,21 @@ def _walk_store_cache_caps(self) -> None: if adjust is not None: adjust(self._pressure_level) + @staticmethod + async def _abort_all_requests(engine: Any, *, spare_parked: bool) -> Any: + """Call ``abort_all_requests``, passing ``spare_parked`` explicitly. + + Engines without parking (DFlash, distributed) have a no-argument hook + and cannot hold parked requests, so the keyword is dropped for them. + A model held by parked requests only is NOT idle (they own a collector, + so ``has_active_requests`` is true): LRU eviction skips it, and only + this explicit abort (``spare_parked=False``) lets an unload drain it. + """ + try: + return await engine.abort_all_requests(spare_parked=spare_parked) + except TypeError: + return await engine.abort_all_requests() + async def _abort_loaded_requests_for_memory_emergency(self) -> int: """Abort active requests on loaded models without unloading them.""" aborted_total = 0 @@ -1584,7 +1599,11 @@ async def _abort_loaded_requests_for_memory_emergency(self) -> int: continue try: - result = abort_all() + # Emergency: parked requests are aborted too. + try: + result = abort_all(spare_parked=False) + except TypeError: + result = abort_all() if inspect.isawaitable(result): result = await result except Exception as exc: # noqa: BLE001 @@ -1905,7 +1924,11 @@ async def _check_and_enforce(self) -> None: and entry.engine is not None and hasattr(entry.engine, "abort_all_requests") ): - result = await entry.engine.abort_all_requests() + # The model is about to be unloaded: parked + # requests would be orphaned, abort them too. + result = await self._abort_all_requests( + entry.engine, spare_parked=False + ) aborted = max(0, int(result or 0)) if aborted > 0: logger.warning( @@ -1934,7 +1957,13 @@ async def _check_and_enforce(self) -> None: and entry.engine is not None and hasattr(entry.engine, "abort_all_requests") ): - aborted = await entry.engine.abort_all_requests() + # Only the non-emergency path keeps the model + # loaded and lets parked requests resume; an + # emergency unload must abort them, or they keep + # the engine non-idle and the unload never drains. + aborted = await self._abort_all_requests( + entry.engine, spare_parked=not emergency + ) if not emergency: logger.warning( "Hard memory pressure: aborted %d request(s) on " diff --git a/tests/test_engine_core.py b/tests/test_engine_core.py index 60df9862f6..d9db219f3b 100644 --- a/tests/test_engine_core.py +++ b/tests/test_engine_core.py @@ -1281,10 +1281,10 @@ async def test_abort_all_requests_skips_requests_already_aborted( engine.close() @pytest.mark.asyncio - async def test_abort_all_requests_leaves_parked_requests_alone( + async def test_abort_all_requests_spares_parked_only_when_asked( self, mock_model, mock_tokenizer ): - """A parked request holds no memory; a pressure abort must keep it.""" + """Only the keep-loaded caller may spare parked requests, explicitly.""" with patch("omlx.engine_core.get_registry") as mock_registry: mock_registry.return_value.acquire.return_value = True engine = EngineCore(model=mock_model, tokenizer=mock_tokenizer) @@ -1295,12 +1295,43 @@ async def test_abort_all_requests_leaves_parked_requests_alone( live_id = await engine.add_request(prompt="World") engine.scheduler.requests[parked_id].parked = True - assert await engine.abort_all_requests() == 1 + assert await engine.abort_all_requests(spare_parked=True) == 1 assert engine._output_collectors[parked_id].get_nowait() is None assert engine._output_collectors[live_id].get_nowait().finished - # An explicit reason (manual unload, shutdown) aborts it too. - assert await engine.abort_all_requests(reason="unloading") == 1 + # No implicit default: unload, eviction, emergency and shutdown + # callers pass nothing (or a reason) and abort it too. + assert await engine.abort_all_requests() == 1 + out = engine._output_collectors[parked_id].get_nowait() + assert out.finished and out.error + finally: + await engine.stop() + engine.close() + + @pytest.mark.asyncio + async def test_abort_all_requests_with_reason_aborts_parked( + self, mock_model, mock_tokenizer + ): + """An unload reason aborts parked requests with the unload error.""" + with patch("omlx.engine_core.get_registry") as mock_registry: + mock_registry.return_value.acquire.return_value = True + engine = EngineCore(model=mock_model, tokenizer=mock_tokenizer) + try: + await engine.start() + engine.scheduler.has_requests = lambda: False + parked_id = await engine.add_request(prompt="Hello") + engine.scheduler.requests[parked_id].parked = True + + assert ( + await engine.abort_all_requests( + reason="unloading", error_code="model_unloading" + ) + == 1 + ) + out = engine._output_collectors[parked_id].get_nowait() + assert out.finished and out.error == "unloading" + assert out.error_code == "model_unloading" + assert parked_id in engine.scheduler._pending_abort_ids finally: await engine.stop() engine.close() diff --git a/tests/test_process_memory_enforcer.py b/tests/test_process_memory_enforcer.py index 6205d56b08..244ce287f2 100644 --- a/tests/test_process_memory_enforcer.py +++ b/tests/test_process_memory_enforcer.py @@ -3126,6 +3126,118 @@ def test_disabled_guard_reports_zero_components(self): } +class _ParkedOnlyEngine: + """Engine whose only work is a parked request (owns a collector).""" + + def __init__(self): + # A scheduler with no park/reclaim API: the enforcer goes straight to + # its abort/evict paths instead of deferring. + self._engine = SimpleNamespace( + engine=SimpleNamespace(scheduler=SimpleNamespace()) + ) + self.parked = ["parked-1"] + self.aborted = [] + self.calls = [] + + def has_active_requests(self): + return bool(self.parked) + + async def abort_all_requests(self, *, spare_parked=False): + self.calls.append(spare_parked) + if spare_parked: + return 0 + n = len(self.parked) + self.aborted.extend(self.parked) + self.parked.clear() + return n + + +class TestParkedRequestsOnUnloadPaths: + """Parked requests are spared only where the model stays loaded.""" + + @pytest.mark.asyncio + async def test_idle_lru_eviction_aborts_parked_then_unloads(self, enforcer): + engine = _ParkedOnlyEngine() + entry = _make_entry("idle-model", engine=engine) + other = _make_entry("other", engine=MagicMock()) + enforcer._engine_pool._entries = {"idle-model": entry, "other": other} + enforcer._engine_pool._find_lru_victim.return_value = "idle-model" + + async def fake_unload(model_id): + enforcer._engine_pool._entries[model_id].engine = None + + enforcer._engine_pool._unload_engine.side_effect = fake_unload + + with patch.object( + enforcer, + "_current_usage_bytes", + side_effect=_cycling([15 * 1024**3, 15 * 1024**3, 8 * 1024**3]), + ): + await enforcer._check_and_enforce() + + assert engine.calls == [False] + assert engine.aborted == ["parked-1"] + enforcer._engine_pool._unload_engine.assert_awaited_once_with("idle-model") + + @pytest.mark.asyncio + async def test_emergency_busy_victim_aborts_parked_and_unload_completes( + self, enforcer + ): + engine = _ParkedOnlyEngine() + entry = _make_entry("big-model", engine=engine) + enforcer._engine_pool._entries = {"big-model": entry} + enforcer._engine_pool._find_lru_victim.return_value = None + + with patch.object( + enforcer, + "_current_usage_bytes", + side_effect=_cycling([13 * 1024**3, 13 * 1024**3]), + ): + await enforcer._check_and_enforce() + + assert engine.calls == [False] + assert engine.aborted == ["parked-1"] + # Nothing keeps the engine busy: the pending unload drained at once. + enforcer._engine_pool._unload_engine.assert_awaited_once_with("big-model") + assert entry.pending_unload_reason is None + + @pytest.mark.asyncio + async def test_keep_loaded_hard_path_spares_parked(self, enforcer): + engine = _ParkedOnlyEngine() + entry = _make_entry("big-model", engine=engine) + enforcer._engine_pool._entries = {"big-model": entry} + enforcer._engine_pool._find_lru_victim.return_value = None + + with patch.object( + enforcer, + "_current_usage_bytes", + side_effect=_cycling([11 * 1024**3, 11 * 1024**3]), + ): + await enforcer._check_and_enforce() + + assert engine.calls == [True] + assert engine.parked == ["parked-1"] + enforcer._engine_pool._unload_engine.assert_not_awaited() + assert entry.pending_unload_reason is None + + @pytest.mark.asyncio + async def test_emergency_abort_of_loaded_models_aborts_parked(self, enforcer): + engine = _ParkedOnlyEngine() + enforcer._engine_pool._entries = {"m": _make_entry("m", engine=engine)} + + assert await enforcer._abort_loaded_requests_for_memory_emergency() == 1 + assert engine.calls == [False] + assert engine.parked == [] + + @pytest.mark.asyncio + async def test_engines_without_parking_keep_the_no_argument_hook(self, enforcer): + class Legacy: + async def abort_all_requests(self): + return 2 + + assert await enforcer._abort_all_requests(Legacy(), spare_parked=True) == 2 + + class TestPressureReclaimGrace: """Reclaim-first grace gives pooled Metal buffers a bounded chance to drain before destructive hot-cache shrinking or request aborts.""" From 4fed9d391319e6f1374b3397ec51420187f85fc6 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Thu, 1 Oct 2026 16:27:50 -0600 Subject: [PATCH 11/18] fix(scheduler): bound the park hold gate and let a parked head pass when idle --- omlx/request.py | 1 + omlx/scheduler.py | 18 +++++++++++++++- tests/test_scheduler_park.py | 41 ++++++++++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+), 1 deletion(-) diff --git a/omlx/request.py b/omlx/request.py index 02f00e2677..adfa77c4c4 100644 --- a/omlx/request.py +++ b/omlx/request.py @@ -248,6 +248,7 @@ def vlm_extra_key_ranges_for_cache( # keeps its client stream and place in line and resumes from its last # committed prefix. ``parked`` is True from the park until the resume. parked: bool = False + parked_at: float = 0.0 # time.monotonic() of the latest park park_count: int = 0 # Parks taken so far (bounded by max_parks_per_request) # Request-scoped tool schemas used by protocol output parsers. diff --git a/omlx/scheduler.py b/omlx/scheduler.py index bc6a9a7be6..d5a71e88a0 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -1357,6 +1357,8 @@ def _is_turboquant_kv_family_cache(cache_obj: Any) -> bool: # A pressure monitor that has not reported for this long is considered gone; # parked requests then resume instead of waiting for polls that never come. PARK_SIGNAL_STALE_S = 60.0 +# Longest a parked head holds admission on a non-hard pressure level. +PARK_MAX_HOLD_S = 300.0 class _ParkPins(NamedTuple): @@ -2283,6 +2285,7 @@ def __init__( self._park_settle_polls: int = 0 self._ok_polls: int = 0 self._last_pressure_poll_at: float | None = None + self._last_pressure_level: str = "ok" self._park_pins: dict[str, _ParkPins] = {} self._park_stats: dict[str, int] = { "parks": 0, @@ -11855,6 +11858,7 @@ def note_pressure_poll(self, level: str) -> None: ``ok`` polls (hysteresis against flapping at the watermark). """ self._last_pressure_poll_at = time.monotonic() + self._last_pressure_level = level if level == "ok": self._ok_polls += 1 self._park_settle_polls = 0 @@ -11869,6 +11873,17 @@ def _park_resume_allowed(self) -> bool: need = getattr(self.config, "park_resume_ok_polls", 3) return self._ok_polls >= max(1, need) + def _park_hold_applies(self, head: "Request") -> bool: + """Whether a parked head still blocks admission. + + Never when nothing is admitted (admission must be able to recover), + and not past PARK_MAX_HOLD_S unless the last pressure was hard. + """ + if self._park_resume_allowed() or not self._num_admitted_requests(): + return False + held_s = time.monotonic() - head.parked_at + return held_s < PARK_MAX_HOLD_S or self._last_pressure_level == "hard" + def is_request_parked(self, request_id: str) -> bool: """Whether the request is currently parked (holds no live memory).""" request = self.requests.get(request_id) @@ -11978,6 +11993,7 @@ def _park_prefill(self, request: Request, reason: str) -> None: self.prefilling = deque(r for r in self.prefilling if r.request_id != rid) self._reset_request_for_reprefill(request) request.parked = True + request.parked_at = time.monotonic() request.park_count += 1 self._clear_request_admission_bookkeeping(rid) get_prefill_tracker().remove(rid) @@ -13030,7 +13046,7 @@ def _schedule_waiting_scan( # Parked requests sit at the front in arrival order and resume # only after enough consecutive ok pressure polls; nothing newer # overtakes them while they wait. - if self.waiting[0].parked and not self._park_resume_allowed(): + if self.waiting[0].parked and self._park_hold_applies(self.waiting[0]): break admitted = self._num_admitted_requests() diff --git a/tests/test_scheduler_park.py b/tests/test_scheduler_park.py index 763cc76599..1115a8b9cb 100644 --- a/tests/test_scheduler_park.py +++ b/tests/test_scheduler_park.py @@ -13,6 +13,7 @@ import test_scheduler_prefill_progress_commit as commit_rig from test_scheduler_prefill_progress_commit import BLOCK, _returns_promptly, _Rig +import omlx.scheduler as scheduler_module from omlx.request import Request, RequestStatus, SamplingParams # Controllable commit worker fixture shared with the incremental-commit suite. @@ -209,6 +210,7 @@ def test_a_sole_prefill_is_parkable_when_pressure_comes_from_elsewhere( try: only = submit(rig, "only", PROMPT_A, arrival=1.0) step_until(rig, lambda: prefilling_ids(rig) == ["only"]) + rig.scheduler._park_hold_applies = lambda head: True # isolate the park assert rig.scheduler.request_park_prefill() is True step(rig) assert only.parked and waiting_ids(rig) == ["only"] @@ -280,6 +282,44 @@ def test_no_resume_before_the_required_consecutive_ok_polls(tmp_path, mock_token rig.close() +def _parked_young(rig, level): + prefill_two(rig) + rig.scheduler.request_park_prefill() + step(rig) + assert waiting_ids(rig) == ["young"] + rig.scheduler.note_pressure_poll(level) + return rig.scheduler.requests["young"] + + +def test_parked_head_passes_when_nothing_is_admitted( + tmp_path, mock_tokenizer, monkeypatch +): + rig = make_rig(tmp_path, mock_tokenizer) + try: + _parked_young(rig, "soft") + monkeypatch.setattr(rig.scheduler, "_num_admitted_requests", lambda: 0) + assert rig.scheduler._park_hold_applies(rig.scheduler.waiting[0]) is False + step_until(rig, lambda: "young" in prefilling_ids(rig)) + finally: + rig.close() + + +def test_parked_head_is_released_after_the_max_hold_unless_hard( + tmp_path, mock_tokenizer +): + rig = make_rig(tmp_path, mock_tokenizer) + try: + young = _parked_young(rig, "soft") + scheduler = rig.scheduler + assert scheduler._park_hold_applies(young) is True # fresh park holds + young.parked_at -= scheduler_module.PARK_MAX_HOLD_S + 1 + assert scheduler._park_hold_applies(young) is False # soft: bounded + scheduler.note_pressure_poll("hard") + assert scheduler._park_hold_applies(young) is True # hard: still held + finally: + rig.close() + + def test_new_requests_do_not_overtake_a_parked_one(tmp_path, mock_tokenizer): rig = make_rig(tmp_path, mock_tokenizer) try: @@ -427,6 +467,7 @@ def test_settling_after_a_park_defers_the_abort_for_a_few_polls( try: submit(rig, "only", PROMPT_A, arrival=1.0) step_until(rig, lambda: prefilling_ids(rig) == ["only"]) + rig.scheduler._park_hold_applies = lambda head: True # isolate the park rig.scheduler.request_park_prefill() step(rig) # Memory is returning to the OS; the enforcer must not abort yet. From 5ed4e2256d16ab84998bb1ba8ccfad1e21879684 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Thu, 1 Oct 2026 16:33:09 -0600 Subject: [PATCH 12/18] fix(scheduler): resume parked requests one per window and keep parked 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 --- omlx/scheduler.py | 83 ++++++++++++------ tests/test_scheduler_park.py | 157 ++++++++++++++++++++++++++++++++++- 2 files changed, 214 insertions(+), 26 deletions(-) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index d5a71e88a0..44bdb8ad23 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -2282,8 +2282,15 @@ def __init__( # poll counters are written by the enforcer thread (GIL-atomic) and # consumed on the MLX thread. self._park_requested: bool = False - self._park_settle_polls: int = 0 + # Enforcer polls since the latest park, or None when no park is + # settling. Counted in note_pressure_poll, never per query. + self._polls_since_park: int | None = None self._ok_polls: int = 0 + # Hysteresis between resumes: at most one parked request resumes per + # scheduling pass, and the next one needs a fresh ok streak (or, for + # the max-hold escape, as many polls since the last resume). + self._park_resumed_this_pass: bool = False + self._polls_since_resume: int = 1 << 30 self._last_pressure_poll_at: float | None = None self._last_pressure_level: str = "ok" self._park_pins: dict[str, _ParkPins] = {} @@ -5642,10 +5649,11 @@ def get_active_hot_cache_block_hashes(self) -> set[bytes]: continue if block_hash is not None: hashes.add(bytes(block_hash)) - # Parked requests hold no live table, but their pinned prefix must - # survive a hot-cache shrink too. - for pins in list(self._park_pins.values()): - hashes.update(pins.hashes) + # Parked requests are deliberately absent: parking exists because RAM + # is short, so a shrink may reclaim their blocks. That is safe because + # a dirty hot-cache eviction is written back to the SSD + # (PagedSSDCacheManager._handle_hot_cache_eviction) where the park pin + # keeps them from LRU eviction, and resume restores them from there. return hashes def _clear_memory_admission_blocker(self, request_id: str | None = None) -> None: @@ -11859,9 +11867,12 @@ def note_pressure_poll(self, level: str) -> None: """ self._last_pressure_poll_at = time.monotonic() self._last_pressure_level = level + self._polls_since_resume = min(self._polls_since_resume + 1, 1 << 30) + if self._polls_since_park is not None: + self._polls_since_park += 1 if level == "ok": self._ok_polls += 1 - self._park_settle_polls = 0 + self._polls_since_park = None # pressure gone: nothing left to settle else: self._ok_polls = 0 @@ -11877,12 +11888,20 @@ def _park_hold_applies(self, head: "Request") -> bool: """Whether a parked head still blocks admission. Never when nothing is admitted (admission must be able to recover), - and not past PARK_MAX_HOLD_S unless the last pressure was hard. + and not past PARK_MAX_HOLD_S unless the last pressure was hard. Every + escape resumes one request per scheduling pass, and the max-hold + escape also waits ``park_resume_ok_polls`` polls after the previous + resume, so a burst of resumes cannot re-trigger hard pressure. """ + if self._park_resumed_this_pass: + return True if self._park_resume_allowed() or not self._num_admitted_requests(): return False + need = max(1, getattr(self.config, "park_resume_ok_polls", 3)) held_s = time.monotonic() - head.parked_at - return held_s < PARK_MAX_HOLD_S or self._last_pressure_level == "hard" + if held_s >= PARK_MAX_HOLD_S and self._last_pressure_level != "hard": + return self._polls_since_resume < need + return True def is_request_parked(self, request_id: str) -> bool: """Whether the request is currently parked (holds no live memory).""" @@ -11947,17 +11966,21 @@ def request_park_prefill(self) -> bool: return False if self._park_requested: return True + victim_may_exist = False try: - victim = self._select_park_victim() - except RuntimeError: # queue mutated mid-read on the MLX thread - victim = True - if victim is not None: + victim_may_exist = self._select_park_victim() is not None + except RuntimeError: + # The queues mutated mid-read on the MLX thread; assume a victim + # exists and let the step-boundary selection decide. + victim_may_exist = True + if victim_may_exist: self._park_requested = True return True - if self._park_settle_polls > 0: - self._park_settle_polls -= 1 - return True - return False + # A park just ran and its memory is still returning to the OS. + return ( + self._polls_since_park is not None + and self._polls_since_park <= PARK_SETTLE_POLLS + ) def _process_pending_park(self) -> bool: """Park one victim if the enforcer asked (MLX thread, step start).""" @@ -11970,7 +11993,7 @@ def _process_pending_park(self) -> bool: if victim is None: return False self._park_prefill(victim, reason="hard memory pressure") - self._park_settle_polls = PARK_SETTLE_POLLS + self._polls_since_park = 0 return True def _park_prefill(self, request: Request, reason: str) -> None: @@ -11998,7 +12021,7 @@ def _park_prefill(self, request: Request, reason: str) -> None: self._clear_request_admission_bookkeeping(rid) get_prefill_tracker().remove(rid) # Order matters: pin first, then release the table's own refs. - self._after_commit(rid, lambda: self._pin_parked_blocks(rid)) + self._after_commit(rid, lambda: self._pin_parked_blocks(rid, request)) self._release_paged_cache_for_request(rid) self._drop_boundary_snapshots_for_request(rid) self._enqueue_parked(request) @@ -12031,17 +12054,21 @@ def _enqueue_parked(self, request: Request) -> None: break self.waiting.insert(index, request) - def _pin_parked_blocks(self, request_id: str) -> None: + def _pin_parked_blocks(self, request_id: str, request: Request) -> None: """Hold the committed blocks of a parked request against eviction. Takes one extra block ref per committed block (so the table's own release leaves them referenced) and pins their hashes in the SSD index, whose size enforcement skips them. Skipped when the request - was aborted or already resumed before this deferred step ran. + was aborted, reset or already resumed before this deferred step ran: + the request must still be the registered, parked one. """ - request = self.requests.get(request_id) manager = self.paged_cache_manager - if request is None or not request.parked or manager is None: + if ( + self.requests.get(request_id) is not request + or not request.parked + or manager is None + ): return table = manager.get_block_table(request_id) if not table or not table.block_ids: @@ -12078,7 +12105,11 @@ def _finish_park_resume(self, request: Request) -> None: """Re-admission of a parked request: its fresh lookup holds the blocks.""" self._unpin_parked(request.request_id) request.parked = False - self._park_settle_polls = 0 + self._polls_since_park = None + # One resume per hysteresis window: consume the ok streak. + self._ok_polls = 0 + self._polls_since_resume = 0 + self._park_resumed_this_pass = True self._park_stats["resumes"] += 1 self._park_stats["tokens_preserved"] += request.cached_tokens or 0 logger.info( @@ -12199,6 +12230,8 @@ def _do_abort_request(self, request_id: str) -> bool: self._clear_request_admission_bookkeeping(request_id) self._unpin_parked(request_id) + # A deferred pin step must not re-pin an aborted request's blocks. + request.parked = False # Remove from waiting queue if request.status == RequestStatus.WAITING: @@ -13035,6 +13068,7 @@ def _schedule_waiting_scan( # Track SpecPrefill: these requests must be alone (RoPE patching affects whole model) batch_specprefill_status: bool | None = None + self._park_resumed_this_pass = False while ( self.waiting and self._num_admitted_requests() < self._effective_max_num_seqs() @@ -15585,7 +15619,8 @@ def reset(self) -> None: for parked_id in list(self._park_pins): self._unpin_parked(parked_id) self._park_requested = False - self._park_settle_polls = 0 + self._polls_since_park = None + self._park_resumed_this_pass = False self._prefill_commits.clear() self._cache_freshness_waits.clear() self._prefix_cache_prepared.clear() diff --git a/tests/test_scheduler_park.py b/tests/test_scheduler_park.py index 1115a8b9cb..123722b29b 100644 --- a/tests/test_scheduler_park.py +++ b/tests/test_scheduler_park.py @@ -471,7 +471,10 @@ def test_settling_after_a_park_defers_the_abort_for_a_few_polls( rig.scheduler.request_park_prefill() step(rig) # Memory is returning to the OS; the enforcer must not abort yet. - answers = [rig.scheduler.request_park_prefill() for _ in range(6)] + answers = [] + for _ in range(6): + rig.scheduler.note_pressure_poll("hard") + answers.append(rig.scheduler.request_park_prefill()) assert answers[0] is True assert answers[-1] is False finally: @@ -502,7 +505,6 @@ def test_committed_blocks_are_pinned_while_parked_and_released_after_resume( rig.ssd._evict_tracked_until_size(0) table, remaining = rig.probe(PROMPT_B) assert table is not None and table.num_tokens >= BLOCK - assert scheduler.get_active_hot_cache_block_hashes() >= set(pins.hashes) finish_ok_polls(rig, 1) step_until(rig, lambda: "young" in prefilling_ids(rig)) @@ -611,6 +613,157 @@ def test_reset_and_shutdown_release_every_pin(tmp_path, mock_tokenizer): rig.close() +# --- Leaks, resume bursts, hot cache, settle polls ----------------------------- + + +def test_abort_of_a_parked_request_with_a_commit_in_flight_leaves_no_pins( + tmp_path, mock_tokenizer, gated +): + rig = make_rig(tmp_path, mock_tokenizer, ok_polls=1) + gate = None + try: + scheduler = rig.scheduler + _, young = prefill_two(rig) + gate = gated(rig) + for _ in range(8): + if "young" in scheduler._prefill_commits: + break + scheduler.step() + assert not scheduler._prefill_commits["young"][0].done() + scheduler.request_park_prefill() + scheduler._process_pending_park() + assert scheduler._teardown_pending("young") + + assert scheduler.abort_request("young") + scheduler.step() # the abort runs while the commit is still in flight + gate.release.set() + rig.drain() + step(rig, 3) + + assert not young.parked # an aborted request is no longer parked + assert "young" not in scheduler._park_pins + assert rig.ssd.pinned_block_count == 0 + finally: + if gate is not None: + gate.release.set() + rig.close() + + +def _park_three(rig): + """r1 prefilling (protected); r2, r3, r4 parked, all unpinned-ready.""" + for i, (rid, prompt) in enumerate( + [("r1", PROMPT_A), ("r2", PROMPT_B), ("r3", PROMPT_C), ("r4", PROMPT_D)] + ): + submit(rig, rid, prompt, arrival=float(i + 1), max_tokens=50) + step_until(rig, lambda: len(prefilling_ids(rig)) == 4) + for _ in range(3): + rig.scheduler.request_park_prefill() + step(rig) + assert waiting_ids(rig) == ["r2", "r3", "r4"] + + +def _resumed(rig): + return rig.scheduler.get_park_stats()["resumes"] + + +def test_parked_requests_resume_one_per_hysteresis_window(tmp_path, mock_tokenizer): + rig = make_rig(tmp_path, mock_tokenizer, ok_polls=2) + try: + _park_three(rig) + finish_ok_polls(rig, 2) + step(rig, 2) + assert _resumed(rig) == 1 # not a burst of three + + step(rig, 3) # no new polls: the streak was consumed by the resume + assert _resumed(rig) == 1 + + finish_ok_polls(rig, 2) + step(rig, 2) + assert _resumed(rig) == 2 + finally: + rig.close() + + +def test_the_max_hold_escape_resumes_one_request_at_a_time(tmp_path, mock_tokenizer): + rig = make_rig(tmp_path, mock_tokenizer, ok_polls=3) + try: + _park_three(rig) + rig.scheduler.note_pressure_poll("soft") + for request in list(rig.scheduler.waiting): + request.parked_at -= scheduler_module.PARK_MAX_HOLD_S + 1 + step(rig, 2) + assert _resumed(rig) == 1 + step(rig, 3) # still no polls: the escape does not chain + assert _resumed(rig) == 1 + finally: + rig.close() + + +def test_a_stale_monitor_resumes_one_request_per_step(tmp_path, mock_tokenizer): + rig = make_rig(tmp_path, mock_tokenizer) + try: + _park_three(rig) + rig.scheduler._last_pressure_poll_at = ( + time.monotonic() - scheduler_module.PARK_SIGNAL_STALE_S - 1 + ) + rig.scheduler._schedule_waiting() + assert _resumed(rig) == 1 + finally: + rig.close() + + +def test_a_hot_cache_shrink_reclaims_parked_blocks_that_stay_restorable( + tmp_path, mock_tokenizer +): + rig = make_rig(tmp_path, mock_tokenizer, ok_polls=1) + try: + rig.ssd._hot_cache_max_bytes = 64 * 1024**2 + rig.ssd._hot_cache_enabled = True + old, young = prefill_two(rig) + scheduler = rig.scheduler + scheduler.request_park_prefill() + step(rig) + rig.drain() + pins = scheduler._park_pins["young"] + assert pins.hashes + assert set(pins.hashes) & set(rig.ssd._hot_cache) # blocks sit in RAM + + protected = scheduler.get_active_hot_cache_block_hashes() + assert not protected & set(pins.hashes) # parked blocks are not RAM-pinned + rig.ssd.shrink_hot_cache_to(0, protected_hashes=protected) + assert not set(pins.hashes) & set(rig.ssd._hot_cache) + + # Dirty evictions were written back: SSD LRU still holds them (pinned). + rig.ssd._evict_tracked_until_size(0) + table, _ = rig.probe(PROMPT_B) + assert table is not None and table.num_tokens >= BLOCK + + finish_ok_polls(rig, 1) + step_until(rig, lambda: "young" in prefilling_ids(rig)) + assert young.cached_tokens >= BLOCK + finally: + rig.close() + + +def test_the_settle_window_counts_enforcer_polls_not_queries(tmp_path, mock_tokenizer): + rig = make_rig(tmp_path, mock_tokenizer, max_parks=1) + try: + submit(rig, "only", PROMPT_A, arrival=1.0) + step_until(rig, lambda: prefilling_ids(rig) == ["only"]) + rig.scheduler._park_hold_applies = lambda head: True # isolate the park + rig.scheduler.request_park_prefill() + step(rig) + # Repeated queries within one poll never consume the window. + assert all(rig.scheduler.request_park_prefill() for _ in range(10)) + for _ in range(scheduler_module.PARK_SETTLE_POLLS): + rig.scheduler.note_pressure_poll("hard") + assert rig.scheduler.request_park_prefill() is True + rig.scheduler.note_pressure_poll("hard") + assert rig.scheduler.request_park_prefill() is False + finally: + rig.close() + + # --- Engine bulk abort ------------------------------------------------------------- From 96c8c5cbb0a7bdd37c6bd04d8b1bd416753cd6f3 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Fri, 2 Oct 2026 01:20:51 -0600 Subject: [PATCH 13/18] refactor(scheduler): name the resume-poll saturation sentinel and test lost hot-cache write-back on resume --- omlx/scheduler.py | 11 ++++-- tests/test_scheduler_park.py | 67 ++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+), 2 deletions(-) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 44bdb8ad23..08ed989ea7 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -1359,6 +1359,11 @@ def _is_turboquant_kv_family_cache(cache_obj: Any) -> bool: PARK_SIGNAL_STALE_S = 60.0 # Longest a parked head holds admission on a non-hard pressure level. PARK_MAX_HOLD_S = 300.0 +# Saturation value of ``_polls_since_resume``: "long enough since the last +# resume that the hysteresis gate is open". It is the initial value (no resume +# has happened yet) and the cap that keeps the counter from growing without +# bound; any value above every realistic ``park_resume_ok_polls`` works. +_POLLS_SINCE_RESUME_SATURATION = 1 << 30 class _ParkPins(NamedTuple): @@ -2290,7 +2295,7 @@ def __init__( # scheduling pass, and the next one needs a fresh ok streak (or, for # the max-hold escape, as many polls since the last resume). self._park_resumed_this_pass: bool = False - self._polls_since_resume: int = 1 << 30 + self._polls_since_resume: int = _POLLS_SINCE_RESUME_SATURATION self._last_pressure_poll_at: float | None = None self._last_pressure_level: str = "ok" self._park_pins: dict[str, _ParkPins] = {} @@ -11867,7 +11872,9 @@ def note_pressure_poll(self, level: str) -> None: """ self._last_pressure_poll_at = time.monotonic() self._last_pressure_level = level - self._polls_since_resume = min(self._polls_since_resume + 1, 1 << 30) + self._polls_since_resume = min( + self._polls_since_resume + 1, _POLLS_SINCE_RESUME_SATURATION + ) if self._polls_since_park is not None: self._polls_since_park += 1 if level == "ok": diff --git a/tests/test_scheduler_park.py b/tests/test_scheduler_park.py index 123722b29b..9350dba771 100644 --- a/tests/test_scheduler_park.py +++ b/tests/test_scheduler_park.py @@ -10,6 +10,7 @@ import time from types import SimpleNamespace +import pytest import test_scheduler_prefill_progress_commit as commit_rig from test_scheduler_prefill_progress_commit import BLOCK, _returns_promptly, _Rig @@ -745,6 +746,61 @@ def test_a_hot_cache_shrink_reclaims_parked_blocks_that_stay_restorable( rig.close() +@pytest.mark.parametrize("failure", ["dropped", "raises"]) +def test_resume_degrades_safely_when_the_hot_cache_writeback_is_lost( + tmp_path, mock_tokenizer, caplog, failure +): + """A parked request's dirty hot-cache blocks are reclaimed and the SSD + write-back does not happen (queue unavailable) or fails: resume must fall + back to whatever is restorable, finish the request and leave a log line.""" + import logging + + expected = uninterrupted_output(tmp_path, mock_tokenizer) + rig = make_rig(tmp_path / "park", mock_tokenizer, ok_polls=1) + try: + rig.ssd._hot_cache_max_bytes = 64 * 1024**2 + rig.ssd._hot_cache_enabled = True + old, young = prefill_two(rig) + scheduler = rig.scheduler + scheduler.request_park_prefill() + step(rig) + rig.drain() + pins = scheduler._park_pins["young"] + assert set(pins.hashes) & set(rig.ssd._hot_cache) + + def lost_write(block_hash, entry, **kwargs): + if failure == "raises": + raise OSError("ssd write queue unavailable") + return False + + rig.ssd._enqueue_ssd_write = lost_write + protected = scheduler.get_active_hot_cache_block_hashes() + try: + rig.ssd.shrink_hot_cache_to(0, protected_hashes=protected) + except OSError: + pass # the cache layer may surface the failure; the scheduler must not care + finally: + del rig.ssd._enqueue_ssd_write # back to the real queue for teardown + # Whatever the SSD index still knows is gone too: nothing is restorable. + rig.ssd._evict_tracked_until_size(0) + + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + finish_ok_polls(rig, 1) + step_until(rig, lambda: "young" in prefilling_ids(rig)) + assert any( + "Resumed parked request young" in r.getMessage() for r in caplog.records + ) + assert young.parked is False + outputs = run_to_completion(rig, [old, young]) + assert not [o for o in outputs if o.error] + assert list(young.output_token_ids) == expected + stats = scheduler.get_park_stats() + assert stats["resumes"] == 1 + assert not scheduler._park_pins + finally: + rig.close() + + def test_the_settle_window_counts_enforcer_polls_not_queries(tmp_path, mock_tokenizer): rig = make_rig(tmp_path, mock_tokenizer, max_parks=1) try: @@ -777,3 +833,14 @@ def test_is_request_parked_reads_the_request_flag(): assert Scheduler.is_request_parked(scheduler, "p") is True assert Scheduler.is_request_parked(scheduler, "l") is False assert Scheduler.is_request_parked(scheduler, "missing") is False + + +def test_polls_since_resume_saturates_at_a_named_constant(tmp_path, mock_tokenizer): + rig = make_rig(tmp_path, mock_tokenizer) + try: + cap = scheduler_module._POLLS_SINCE_RESUME_SATURATION + assert rig.scheduler._polls_since_resume == cap + rig.scheduler.note_pressure_poll("ok") + assert rig.scheduler._polls_since_resume == cap # saturated, no growth + finally: + rig.close() From 289a9d46d91e53453a2a2b4378ec35644c762cba Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Fri, 2 Oct 2026 03:15:50 -0600 Subject: [PATCH 14/18] fix(scheduler): commit prefill progress for media prompts and log every 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. --- omlx/scheduler.py | 207 ++++++++-- tests/test_scheduler_prefill_commit_vlm.py | 453 +++++++++++++++++++++ 2 files changed, 632 insertions(+), 28 deletions(-) create mode 100644 tests/test_scheduler_prefill_commit_vlm.py diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 08ed989ea7..81c4131067 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -4637,10 +4637,10 @@ def _chunk_route(n_tokens: int, cache_tokens: int) -> bool: self._emit_prefill_tail_snapshot( request, prompt_cache, total_tokens ) - if vlm_embeds is None: - Scheduler._commit_prefill_progress( - self, request, prompt_cache, base_size + processed_tokens - ) + # Media prompts commit too, under the request's own cache keys. + Scheduler._commit_prefill_progress( + self, request, prompt_cache, base_size + processed_tokens + ) Scheduler._check_post_prefill_memory( self, @@ -8002,6 +8002,28 @@ def _commit_prefill_progress( "Prefill progress commit failed for %s: %s", request.request_id, e ) + def _note_prefill_commit_skip( + self, request: "Request", key: str, detail: str + ) -> None: + """Log why a prefill commit did not run, once per request and reason. + + Every early return of the commit path ends here, so a prefill that + never becomes durable always says why in the server log. + """ + seen = getattr(request, "_prefill_commit_skips", None) + if seen is None: + seen = set() + try: + request._prefill_commit_skips = seen + except AttributeError: + return + if key in seen: + return + seen.add(key) + logger.info( + "Prefill progress commit skipped for %s: %s", request.request_id, detail + ) + def _commit_prefill_progress_unchecked( self, request: "Request", @@ -8010,6 +8032,7 @@ def _commit_prefill_progress_unchecked( commit_blocks: int, ) -> None: rid = request.request_id + skip = self._note_prefill_commit_skip block_size = self.config.paged_cache_block_size if ( block_size <= 0 @@ -8018,30 +8041,89 @@ def _commit_prefill_progress_unchecked( or self.paged_ssd_cache_manager is None or self._store_cache_executor is None ): + skip( + request, + "stores", + "no paged block size, prefix cache, SSD cache or store executor", + ) + return + if getattr(request, "skip_cache_store", False): + skip(request, "skip_cache_store", "the request opted out of cache stores") + return + if self._model_has_unreconstructible_cache(): + skip( + request, "unreconstructible", "the model's cache layout is not storable" + ) return # Prompts that are not a plain token prefix cannot be keyed by token. if ( - getattr(request, "vlm_extra_keys_for_cache", None) - or getattr(request, "vlm_extra_key_ranges_for_cache", None) - or getattr(request, "specprefill_indices", None) is not None + getattr(request, "specprefill_indices", None) is not None or self._specprefill_active_request_id == rid ): + skip(request, "specprefill", "sparse prefill (SpecPrefill) is active") + return + # Media prompts commit under the cache keys their final store uses. Those + # keys come from the whole prompt before prefill starts and a block's key + # depends only on where the block ends, never on later tokens, so the + # committed prefix is exactly what a re-issue's lookup asks for. Models + # that insist on prefilling the media prefix in one piece cannot resume + # from a committed part of it. + extra_keys = getattr(request, "vlm_extra_keys_for_cache", None) + extra_start = getattr(request, "vlm_extra_key_token_start_for_cache", None) + extra_ranges = getattr(request, "vlm_extra_key_ranges_for_cache", None) + has_media_keys = bool(extra_keys or extra_ranges) + if has_media_keys and self._minimum_prefill_prefix(request) > 0: + skip( + request, + "atomic_media_prefix", + "the model needs an atomic multimodal prefix", + ) return prompt = request.prompt_token_ids aligned = min(total_tokens, len(prompt)) // block_size * block_size self._reap_prefill_commit(rid) if rid in self._prefill_commits: - return # previous commit still running + skip(request, "in_flight", "the previous commit is still running") + return table = self.paged_cache_manager.get_block_table(rid) existing = table.num_tokens if table else 0 - if existing % block_size or (aligned - existing) // block_size < commit_blocks: + if existing % block_size: + skip( + request, + "unaligned_table", + f"the block table holds {existing} tokens, off the " + f"{block_size}-token block grid", + ) + return + if (aligned - existing) // block_size < commit_blocks: + skip( + request, + "below_threshold", + f"{(aligned - existing) // block_size} of {commit_blocks} " + f"blocks complete past {existing} tokens (first commit pending)", + ) return if self._prefill_commit_blocked_by_pressure(): + try: + usage = f"{self._current_usage_bytes() / 1024**3:.1f}GB" + except Exception: + usage = "unknown" + skip( + request, + "pressure", + f"memory usage {usage} is at or above the soft limit " + f"{self._memory_limit_bytes / 1024**3:.1f}GB", + ) return window = self._prefill_commit_window(prompt_cache, existing, aligned) if window is None: + skip( + request, + "layout", + "composite or non-standard sliceable cache layers", + ) if not getattr(self, "_prefill_commit_layout_logged", False): self._prefill_commit_layout_logged = True logger.info( @@ -8056,12 +8138,29 @@ def _commit_prefill_progress_unchecked( if _prompt_cache_needs_snapshots(prompt_cache): override = self._get_boundary_store_override(rid, tokens) if override is None: + held = len(self._boundary_cache_snapshots.get(rid) or {}) + skip( + request, + "no_snapshot", + f"no recurrent-state snapshot at or before {aligned} " + f"tokens ({held} held)", + ) return tokens, boundary_cache, _, provider = override - if ( - getattr(provider, "tail_terminal_token_count", None) is not None - or len(tokens) <= existing - ): + if getattr(provider, "tail_terminal_token_count", None) is not None: + skip( + request, + "tail_terminal", + "the newest snapshot is an off-grid tail", + ) + return + if len(tokens) <= existing: + skip( + request, + "no_new_snapshot", + f"the newest snapshot ({len(tokens)} tokens) is not " + f"past the committed {existing}", + ) return extracted = self._merge_boundary_with_full_cache( boundary_cache, extracted @@ -8084,13 +8183,17 @@ def _commit_prefill_progress_unchecked( extracted, model_cache_config, provider, + extra_key_args=( + (extra_keys, extra_start, extra_ranges) if has_media_keys else None + ), ) self._prefill_commits[rid] = (future, len(tokens)) - logger.debug( - "Committing prefill progress for %s: %d -> %d tokens", + logger.info( + "Committing prefill progress for %s: tokens [%d, %d)%s", rid, existing, len(tokens), + " under media cache keys" if has_media_keys else "", ) def _commit_prefill_worker( @@ -8100,9 +8203,13 @@ def _commit_prefill_worker( window_cache: list[Any], model_cache_config: Any | None, snapshots: Any | None, + extra_key_args: tuple[Any, Any, Any] | None = None, ) -> bool: """Store a committed prefill window; True when the table covers it. + ``extra_key_args`` are the request's media cache keys (keys, token + start, ranges), passed exactly as its final store passes them. + Cancellation is checked under ``_commit_store_lock`` before the store call, the only step that touches the stores; shutdown takes that lock to learn that no store call is active. @@ -8110,15 +8217,16 @@ def _commit_prefill_worker( with self._commit_store_lock: if self._commit_cancelled.is_set(): return False + extra_keys, extra_start, extra_ranges = extra_key_args or (None, None, None) self._async_store_cache_worker( request_id, tokens, window_cache, model_cache_config, snapshots, - None, - None, - None, + extra_keys, + extra_start, + extra_ranges, True, incremental_commit=True, ) @@ -11922,25 +12030,66 @@ def get_park_stats(self) -> dict[str, int]: stats["pinned_requests"] = len(self._park_pins) return stats - def _parkable_prefills(self) -> list[Request]: - """Chunked prefills that can be parked safely. + def _park_exclusion_reason(self, request: Request) -> str | None: + """Why ``request`` cannot be parked now, or None when it can. Only requests in the chunked-prefill loop qualify: their state lives - between steps. External-loop prefills (non-chunked, VLM) run to - completion inside one ``_schedule_waiting`` call and are never - between steps; VLM embeds and SpecPrefill patch model-wide state, so - they are excluded as well. + between steps. External-loop prefills (non-chunked, media prompts) run + to completion inside one ``_schedule_waiting`` call and are never + between steps; media embeddings and SpecPrefill patch model-wide state, + so they are excluded as well. A text prompt on a VLM engine takes the + chunked loop like any other model and is parkable. """ budget = getattr(self.config, "max_parks_per_request", 3) + if request.request_id in self.running: + return "decoding, not in chunked prefill" + if request.park_count >= budget: + return f"park budget spent ({request.park_count}/{budget})" + if request.specprefill_indices is not None: + return "SpecPrefill sparse prefill patches model-wide state" + if request.vlm_inputs_embeds is not None: + return ( + "multimodal prompt (fused media embeddings) prefills in the " + "external loop, not between steps" + ) + if request.request_id not in self._prefill_states: + return "prefill runs in the external loop, not between steps" + return None + + def _parkable_prefills(self) -> list[Request]: + """Chunked prefills that can be parked safely.""" return [ request for request in list(self.prefilling) - if request.request_id in self._prefill_states - and request.park_count < budget - and request.specprefill_indices is None - and request.vlm_inputs_embeds is None + if self._park_exclusion_reason(request) is None ] + def _log_no_parkable_victim(self) -> None: + """Say once per request why a park was wanted and nobody could be parked.""" + try: + admitted = list(self.requests.values()) + queued = {r.request_id for r in list(self.waiting)} + except RuntimeError: + return # the queues mutated mid-read on the MLX thread + for request in admitted: + if request.request_id in queued or request.is_finished(): + continue + reason = self._park_exclusion_reason(request) + if reason is None or reason in getattr(request, "_park_skip_logged", ()): + continue + try: + request._park_skip_logged = ( + *getattr(request, "_park_skip_logged", ()), + reason, + ) + except AttributeError: + continue + logger.info( + "Park skipped for %s: %s (memory pressure falls back to abort)", + request.request_id, + reason, + ) + def _select_park_victim(self) -> Request | None: """Most recent arrival first; the oldest admitted request is protected. @@ -11983,6 +12132,7 @@ def request_park_prefill(self) -> bool: if victim_may_exist: self._park_requested = True return True + self._log_no_parkable_victim() # A park just ran and its memory is still returning to the OS. return ( self._polls_since_park is not None @@ -11998,6 +12148,7 @@ def _process_pending_park(self) -> bool: return False victim = self._select_park_victim() if victim is None: + self._log_no_parkable_victim() return False self._park_prefill(victim, reason="hard memory pressure") self._polls_since_park = 0 diff --git a/tests/test_scheduler_prefill_commit_vlm.py b/tests/test_scheduler_prefill_commit_vlm.py new file mode 100644 index 0000000000..a08ff346a0 --- /dev/null +++ b/tests/test_scheduler_prefill_commit_vlm.py @@ -0,0 +1,453 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Incremental prefill commit on the VLM engine path. + +``VLMBatchedEngine`` runs a text prompt through the same chunked prefill as any +other engine, but a prompt whose conversation carries an image (pi resends the +whole history every turn) arrives with fused embeddings and request-wide media +cache keys. It takes the external prefill loop instead. These tests drive that +path against a small initialized Qwen3.5 hybrid wrapped to accept +``inputs_embeds`` the way the mlx-vlm language model does. +""" + +import logging + +import mlx.core as mx +import mlx.nn as nn +import pytest +from test_scheduler_prefill_progress_commit import ( # noqa: F401 + BLOCK, + PROMPT, + _decode_to_finish, + _Rig, + gated, +) + +from omlx.request import Request, SamplingParams + +IMAGE_KEY = ("image-a",) +IMAGE_START = 6 # inside the second block: block one stays a plain text prefix + + +class _VLMLikeModel(nn.Module): + """Hybrid text model with the mlx-vlm language-model call signature.""" + + def __init__(self, inner, minimum_prefix=0): + super().__init__() + self.inner = inner + self._minimum_prefix = minimum_prefix + + @property + def layers(self): + return self.inner.layers + + def make_cache(self): + return self.inner.make_cache() + + def embed(self, tokens): + return self.inner.language_model.model.embed_tokens(mx.array([tokens])) + + def clear_vlm_position_state(self): + pass + + def __call__(self, inputs, cache=None, inputs_embeds=None, **_): + return self.inner(inputs, cache=cache, input_embeddings=inputs_embeds) + + def minimum_prefill_prefix(self, tokens): + return self._minimum_prefix + + +@pytest.fixture +def split(request): + return request.param + + +def _rig(tmp_path, tokenizer, split, *, commit_blocks=2, minimum_prefix=0): + rig = _Rig(tmp_path, tokenizer, split=split, commit_blocks=commit_blocks) + wrapped = _VLMLikeModel(rig.model, minimum_prefix) + rig.scheduler.model = wrapped + rig.wrapped = wrapped + return rig + + +def _media_request(rig, rid="mm", prompt=PROMPT, **overrides): + embeds = rig.wrapped.embed(list(prompt)) + request = Request( + request_id=rid, + prompt=list(prompt), + sampling_params=SamplingParams(max_tokens=1), + vlm_inputs_embeds=embeds, + vlm_image_hash=IMAGE_KEY[0], + vlm_cache_key_start=IMAGE_START, + **overrides, + ) + rig.scheduler.add_request(request) + rig.scheduler.waiting.clear() + request.remaining_tokens = list(prompt) + return request, embeds + + +def _prefill_externally(rig, request, embeds): + rig.scheduler._do_external_prefill( + request, list(request.prompt_token_ids), None, vlm_embeds=(embeds, {}, 0) + ) + rig.drain() + + +def _lookup(rig, tokens, keyed): + kwargs = ( + {"extra_keys": IMAGE_KEY, "extra_key_token_start": IMAGE_START} if keyed else {} + ) + return rig.prefix.fetch_cache("probe", list(tokens), **kwargs) + + +@pytest.mark.parametrize( + "split", [False, True], ids=["inline-gdn", "split-gdn"], indirect=True +) +def test_media_prompt_commits_progress_under_its_own_cache_keys( + tmp_path, mock_tokenizer, split +): + rig = _rig(tmp_path, mock_tokenizer, split) + try: + request, embeds = _media_request(rig) + _prefill_externally(rig, request, embeds) + assert rig.table_tokens("mm") == 4 * BLOCK + + # A re-issue of the same media prompt resumes at the committed boundary + # and the restored prefix equals a cold forward pass. + assert rig.scheduler._do_abort_request("mm") + table, remaining = _lookup(rig, PROMPT, keyed=True) + assert table is not None and table.num_tokens == 4 * BLOCK + assert remaining == PROMPT[4 * BLOCK :] + restored = rig.prefix.reconstruct_cache(table) + assert restored is not None + with mx.stream(rig.scheduler._stream): + warm = rig.wrapped( + mx.array([remaining]), + cache=restored, + inputs_embeds=rig.wrapped.embed(remaining), + ) + cold = rig.wrapped( + mx.array([PROMPT]), + cache=rig.wrapped.make_cache(), + inputs_embeds=rig.wrapped.embed(PROMPT), + ) + mx.eval(warm, cold) + assert mx.allclose(warm[:, -1], cold[:, -1], atol=1e-4) + finally: + rig.close() + + +@pytest.mark.parametrize( + "split", [False, True], ids=["inline-gdn", "split-gdn"], indirect=True +) +def test_committed_media_blocks_are_not_visible_to_a_text_only_lookup( + tmp_path, mock_tokenizer, split +): + rig = _rig(tmp_path, mock_tokenizer, split) + try: + request, embeds = _media_request(rig) + _prefill_externally(rig, request, embeds) + assert rig.scheduler._do_abort_request("mm") + + # Block one ends before the image starts, so it is an ordinary text + # prefix; every later block carries the media key and must not match. + table, remaining = _lookup(rig, PROMPT, keyed=False) + assert table is not None and table.num_tokens == BLOCK + assert remaining == PROMPT[BLOCK:] + finally: + rig.close() + + +@pytest.mark.parametrize( + "split", [False, True], ids=["inline-gdn", "split-gdn"], indirect=True +) +def test_media_commit_matches_the_final_store_keys(tmp_path, mock_tokenizer, split): + rig = _rig(tmp_path, mock_tokenizer, split) + try: + request, embeds = _media_request(rig) + _prefill_externally(rig, request, embeds) + committed = [ + rig.paged.allocated_blocks[b].block_hash + for b in rig.paged.get_block_table("mm").block_ids + ] + # The chain the final store would produce for the same prompt and keys. + from omlx.cache.paged_cache import compute_block_hash, resolve_block_extra_keys + + parent, expected = None, [] + for start in range(0, 4 * BLOCK, BLOCK): + parent = compute_block_hash( + parent, + PROMPT[start : start + BLOCK], + extra_keys=resolve_block_extra_keys( + start + BLOCK, + extra_keys=IMAGE_KEY, + extra_key_token_start=IMAGE_START, + ), + model_name=rig.paged.model_name, + ) + expected.append(parent) + assert committed == expected + finally: + rig.close() + + +@pytest.mark.parametrize("split", [False], ids=["inline-gdn"], indirect=True) +def test_models_needing_an_atomic_media_prefix_do_not_commit( + tmp_path, mock_tokenizer, split, caplog +): + rig = _rig(tmp_path, mock_tokenizer, split, minimum_prefix=BLOCK) + try: + request, embeds = _media_request(rig) + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + _prefill_externally(rig, request, embeds) + assert rig.table_tokens("mm") == 0 + assert any( + "skipped for mm" in r.getMessage() and "atomic" in r.getMessage() + for r in caplog.records + ) + finally: + rig.close() + + +@pytest.mark.parametrize( + "split", [False, True], ids=["inline-gdn", "split-gdn"], indirect=True +) +def test_text_prompt_on_the_vlm_engine_commits_through_chunked_prefill( + tmp_path, mock_tokenizer, split +): + rig = _rig(tmp_path, mock_tokenizer, split) + try: + request = Request( + request_id="txt", + prompt=list(PROMPT), + sampling_params=SamplingParams(max_tokens=1), + ) + rig.scheduler.add_request(request) + rig.scheduler.waiting.clear() + request.remaining_tokens = list(PROMPT) + state = rig.scheduler._begin_prefill(request, list(PROMPT), None) + rig.step(state, 3) + assert rig.table_tokens("txt") == 2 * BLOCK + finally: + rig.close() + + +# --- Observability: a prefill that is not durable always says why --------------- + + +def _info(caplog, needle): + return [ + r.getMessage() + for r in caplog.records + if r.levelno == logging.INFO and needle in r.getMessage() + ] + + +def _chunked_text_prefill(rig, rid="r1", chunks=4): + request = Request( + request_id=rid, + prompt=list(PROMPT), + sampling_params=SamplingParams(max_tokens=1), + ) + rig.scheduler.add_request(request) + rig.scheduler.waiting.clear() + request.remaining_tokens = list(PROMPT) + state = rig.scheduler._begin_prefill(request, list(PROMPT), None) + rig.step(state, chunks) + return request + + +@pytest.mark.parametrize("split", [False], ids=["inline-gdn"], indirect=True) +def test_each_successful_commit_logs_its_token_range_once( + tmp_path, mock_tokenizer, split, caplog +): + rig = _rig(tmp_path, mock_tokenizer, split) + try: + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + _chunked_text_prefill(rig) + assert _info(caplog, "Committing prefill progress for r1") == [ + "Committing prefill progress for r1: tokens [0, 8)", + "Committing prefill progress for r1: tokens [8, 16)", + ] + finally: + rig.close() + + +@pytest.mark.parametrize("split", [False], ids=["inline-gdn"], indirect=True) +def test_media_commit_log_names_the_media_keys(tmp_path, mock_tokenizer, split, caplog): + rig = _rig(tmp_path, mock_tokenizer, split) + try: + request, embeds = _media_request(rig) + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + _prefill_externally(rig, request, embeds) + assert _info( + caplog, "Committing prefill progress for mm: tokens [0, 8) under media" + ) + finally: + rig.close() + + +@pytest.mark.parametrize("split", [False], ids=["inline-gdn"], indirect=True) +def test_waiting_for_the_first_commit_is_logged_once_per_request( + tmp_path, mock_tokenizer, split, caplog +): + rig = _rig(tmp_path, mock_tokenizer, split, commit_blocks=3) + try: + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + _chunked_text_prefill(rig, chunks=2) + lines = _info(caplog, "Prefill progress commit skipped for r1") + assert len(lines) == 1 + assert "of 3 blocks complete" in lines[0] + finally: + rig.close() + + +@pytest.mark.parametrize("split", [False], ids=["inline-gdn"], indirect=True) +def test_pressure_skip_is_logged_once_with_the_usage( + tmp_path, mock_tokenizer, split, caplog, monkeypatch +): + rig = _rig(tmp_path, mock_tokenizer, split) + try: + monkeypatch.setattr( + rig.scheduler, "_prefill_commit_blocked_by_pressure", lambda: True + ) + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + _chunked_text_prefill(rig, chunks=4) + lines = [ + m + for m in _info(caplog, "Prefill progress commit skipped for r1") + if "soft limit" in m + ] + assert len(lines) == 1 + assert rig.table_tokens("r1") == 0 + finally: + rig.close() + + +@pytest.mark.parametrize("split", [False], ids=["inline-gdn"], indirect=True) +def test_missing_snapshot_skip_is_logged_once( + tmp_path, mock_tokenizer, split, caplog, monkeypatch +): + rig = _rig(tmp_path, mock_tokenizer, split) + try: + monkeypatch.setattr( + rig.scheduler, "_get_boundary_store_override", lambda *a: None + ) + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + _chunked_text_prefill(rig, chunks=4) + lines = _info(caplog, "no recurrent-state snapshot") + assert len(lines) == 1 and "skipped for r1" in lines[0] + finally: + rig.close() + + +@pytest.mark.parametrize("split", [False], ids=["inline-gdn"], indirect=True) +def test_opt_out_and_specprefill_skips_say_so(tmp_path, mock_tokenizer, split, caplog): + rig = _rig(tmp_path, mock_tokenizer, split) + try: + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + request, embeds = _media_request(rig, rid="opt", skip_cache_store=True) + _prefill_externally(rig, request, embeds) + request, embeds = _media_request(rig, rid="sp") + request.specprefill_indices = mx.array([0, 1]) + _prefill_externally(rig, request, embeds) + assert _info(caplog, "skipped for opt: the request opted out") + assert _info(caplog, "skipped for sp: sparse prefill") + assert rig.table_tokens("opt") == 0 and rig.table_tokens("sp") == 0 + finally: + rig.close() + + +# --- Park on the VLM engine ------------------------------------------------------ + + +def _park_rig(tmp_path, tokenizer): + import test_scheduler_park as park + + rig = park.make_rig(tmp_path, tokenizer) + rig.wrapped = rig.scheduler.model = _VLMLikeModel(rig.model) + return park, rig + + +@pytest.mark.parametrize("split", [False], ids=["inline-gdn"], indirect=True) +def test_text_prompt_in_chunked_prefill_on_the_vlm_engine_is_a_park_victim( + tmp_path, mock_tokenizer, split +): + park, rig = _park_rig(tmp_path, mock_tokenizer) + try: + request = park.submit(rig, "txt", park.PROMPT_A, arrival=1.0) + park.step_until( + rig, + lambda: park.prefilling_ids(rig) == ["txt"] + and rig.table_tokens("txt") >= BLOCK, + ) + assert rig.scheduler._park_exclusion_reason(request) is None + assert rig.scheduler._select_park_victim() is request + assert rig.scheduler.request_park_prefill() is True + finally: + rig.close() + + +@pytest.mark.parametrize("split", [False], ids=["inline-gdn"], indirect=True) +def test_exclusion_reasons_name_each_unparkable_case(tmp_path, mock_tokenizer, split): + park, rig = _park_rig(tmp_path, mock_tokenizer) + try: + scheduler = rig.scheduler + media, _ = _media_request(rig, rid="media") + scheduler.prefilling.append(media) + scheduler._prefill_states["media"] = object() + assert "multimodal" in scheduler._park_exclusion_reason(media) + + sparse = Request( + request_id="sparse", prompt=[3, 4], sampling_params=SamplingParams() + ) + sparse.specprefill_indices = mx.array([0]) + assert "SpecPrefill" in scheduler._park_exclusion_reason(sparse) + + external = Request( + request_id="ext", prompt=[3, 4], sampling_params=SamplingParams() + ) + assert "external loop" in scheduler._park_exclusion_reason(external) + + spent = Request( + request_id="spent", prompt=[3, 4], sampling_params=SamplingParams() + ) + spent.park_count = scheduler.config.max_parks_per_request + assert "park budget spent" in scheduler._park_exclusion_reason(spent) + + decoding = Request( + request_id="dec", prompt=[3, 4], sampling_params=SamplingParams() + ) + scheduler.running["dec"] = decoding + assert scheduler._park_exclusion_reason(decoding) == ( + "decoding, not in chunked prefill" + ) + finally: + rig.close() + + +@pytest.mark.parametrize("split", [False], ids=["inline-gdn"], indirect=True) +def test_no_parkable_victim_is_logged_once_per_request_with_its_reason( + tmp_path, mock_tokenizer, split, caplog +): + park, rig = _park_rig(tmp_path, mock_tokenizer) + try: + scheduler = rig.scheduler + decoding = Request( + request_id="dec", prompt=[3, 4], sampling_params=SamplingParams() + ) + scheduler.requests["dec"] = decoding + scheduler.running["dec"] = decoding + external = Request( + request_id="ext", prompt=[3, 4], sampling_params=SamplingParams() + ) + scheduler.requests["ext"] = external # admitted, in the external loop + with caplog.at_level(logging.INFO, logger="omlx.scheduler"): + assert scheduler.request_park_prefill() is False + assert scheduler.request_park_prefill() is False + lines = _info(caplog, "Park skipped for") + assert len(lines) == 2 + assert any("dec: decoding, not in chunked prefill" in m for m in lines) + assert any("ext: prefill runs in the external loop" in m for m in lines) + finally: + rig.close() From 7be02915d6cd5b2dda84f371bd2a21690f87e9c2 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Fri, 2 Oct 2026 03:15:58 -0600 Subject: [PATCH 15/18] fix(scheduler): keep shutdown waits on prefill commits inside the teardown 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. --- omlx/scheduler.py | 42 +++++++++-- tests/test_scheduler_prefill_commit_vlm.py | 87 ++++++++++++++++++++++ 2 files changed, 121 insertions(+), 8 deletions(-) diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 81c4131067..6c7d545121 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -1337,14 +1337,18 @@ def _is_turboquant_kv_family_cache(cache_obj: Any) -> bool: # Bounded wait for in-flight prefill commits at shutdown only; the hot path -# never waits (see Scheduler._after_commit). -PREFILL_COMMIT_SHUTDOWN_WAIT_S = 30.0 +# never waits (see Scheduler._after_commit). The three shutdown waits below add +# up to at most 20s, a third of FATAL_TEARDOWN_TIMEOUT_S, so a stuck commit can +# never eat the engine-teardown watchdog's budget before the SSD stores close. +PREFILL_COMMIT_SHUTDOWN_WAIT_S = 10.0 # A teardown deferred behind a commit that has not finished after this long # is logged once; it stays pending and is dropped at shutdown. PREFILL_COMMIT_STUCK_LOG_S = 60.0 # Extra bounded wait at shutdown for a commit worker that is inside a store # call after the cancel flag is set. Past it the stores are left unclosed. -PREFILL_COMMIT_CANCEL_WAIT_S = 10.0 +PREFILL_COMMIT_CANCEL_WAIT_S = 5.0 +# Bound on clearing the commit worker's MLX streams at shutdown. +PREFILL_COMMIT_STREAM_CLEANUP_WAIT_S = 5.0 # Bound on the final-store worker waiting for the request's in-flight commit. # Past it the final store is skipped so a stuck commit cannot hold the store # worker (and the gate slots queued behind it). @@ -2902,18 +2906,33 @@ def _async_store_cache_worker( """ self._store_cache_thread_id = threading.get_ident() if after_commit is not None: - done, _pending = concurrent.futures.wait( - [after_commit], timeout=PREFILL_COMMIT_FINAL_STORE_WAIT_S - ) + # Poll in short slices so a shutdown that cancels the commits + # frees this worker at once instead of after the full bound, + # which would hold the teardown (and its watchdog) behind it. + deadline = time.monotonic() + PREFILL_COMMIT_FINAL_STORE_WAIT_S + done = False + while not done: + left = deadline - time.monotonic() + if left <= 0 or self._commit_cancelled.is_set(): + break + done_set, _pending = concurrent.futures.wait( + [after_commit], timeout=min(1.0, left) + ) + done = bool(done_set) if not done: # Skip this final store; table and snapshot teardown stays # deferred behind the commit (scheduler thread), the gate slot # is released when the drain sees this future done. logger.warning( "Skipping final store for %s: its prefill commit did not " - "finish within %.0fs", + "finish within %.0fs%s", request_id, PREFILL_COMMIT_FINAL_STORE_WAIT_S, + ( + " (cancelled at shutdown)" + if self._commit_cancelled.is_set() + else "" + ), ) self._skipped_final_stores.add(request_id) return @@ -15876,6 +15895,11 @@ def _shutdown_prefill_commits(self) -> bool: directories and the process is going away). """ executor = self._prefill_commit_executor + teardown = getattr(self, "_engine_teardown", None) + if teardown is not None and self._prefill_commits: + # A commit that is still writing counts as persistence progress + # for the teardown watchdog; a stuck one does not. + teardown.set_phase("prefill_commits", self._store_persistence_progress) stragglers = self._wait_for_prefill_commits(PREFILL_COMMIT_SHUTDOWN_WAIT_S) store_busy = False if stragglers: @@ -15897,7 +15921,9 @@ def _shutdown_prefill_commits(self) -> bool: ) elif executor is not None: try: - executor.submit(clear_thread_streams).result(timeout=10) + executor.submit(clear_thread_streams).result( + timeout=PREFILL_COMMIT_STREAM_CLEANUP_WAIT_S + ) except Exception as e: logger.warning("Prefill commit worker stream cleanup failed: %s", e) self._deferred_teardowns.clear() diff --git a/tests/test_scheduler_prefill_commit_vlm.py b/tests/test_scheduler_prefill_commit_vlm.py index a08ff346a0..e123d2e09a 100644 --- a/tests/test_scheduler_prefill_commit_vlm.py +++ b/tests/test_scheduler_prefill_commit_vlm.py @@ -451,3 +451,90 @@ def test_no_parkable_victim_is_logged_once_per_request_with_its_reason( assert any("ext: prefill runs in the external loop" in m for m in lines) finally: rig.close() + + +# --- Teardown budget: our waits must fit inside the engine watchdog -------------- + + +def test_shutdown_commit_waits_fit_a_fraction_of_the_teardown_watchdog(): + import omlx.scheduler as sm + from omlx.utils.fatal import FATAL_TEARDOWN_TIMEOUT_S + + worst = ( + sm.PREFILL_COMMIT_SHUTDOWN_WAIT_S + + sm.PREFILL_COMMIT_CANCEL_WAIT_S + + sm.PREFILL_COMMIT_STREAM_CLEANUP_WAIT_S + ) + assert worst <= FATAL_TEARDOWN_TIMEOUT_S / 2 + + +def _stuck_final_store(rig, gated, monkeypatch): # noqa: F811 + """A final store queued behind a commit that never ends (gate held).""" + import omlx.scheduler as sm + + gate = gated(rig) + request, state = rig.start("r1", PROMPT) + while not rig.scheduler._step_prefill_chunk(state): + pass + assert gate.entered.wait(20) + finished = _decode_to_finish(rig, request, state) + rig.scheduler._cleanup_finished(finished) + fatal = [] + monkeypatch.setattr(sm, "fatal_exit", lambda msg: fatal.append(msg)) + return gate, fatal + + +@pytest.mark.parametrize("split", [False], ids=["inline-gdn"], indirect=True) +def test_shutdown_cancels_a_final_store_waiting_on_a_stuck_commit( + tmp_path, mock_tokenizer, split, monkeypatch, gated # noqa: F811 +): + import time + + import omlx.scheduler as sm + + # The final store would wait a full minute for the commit; the teardown + # watchdog allows far less. Shutdown must not inherit that wait. + monkeypatch.setattr(sm, "PREFILL_COMMIT_FINAL_STORE_WAIT_S", 60.0) + monkeypatch.setattr(sm, "PREFILL_COMMIT_SHUTDOWN_WAIT_S", 0.3) + monkeypatch.setattr(sm, "PREFILL_COMMIT_CANCEL_WAIT_S", 0.3) + monkeypatch.setattr(sm, "FATAL_TEARDOWN_TIMEOUT_S", 5.0) + rig = _rig(tmp_path, mock_tokenizer, split) + try: + gate, fatal = _stuck_final_store(rig, gated, monkeypatch) + started = time.monotonic() + rig.scheduler.shutdown() + elapsed = time.monotonic() - started + assert fatal == [] + assert elapsed < 4.0 + finally: + gate.release.set() + rig.close() + + +@pytest.mark.parametrize("split", [False], ids=["inline-gdn"], indirect=True) +def test_shutdown_reports_commit_progress_to_the_teardown_watchdog( + tmp_path, mock_tokenizer, split, monkeypatch, gated # noqa: F811 +): + import omlx.scheduler as sm + + monkeypatch.setattr(sm, "PREFILL_COMMIT_SHUTDOWN_WAIT_S", 0.3) + monkeypatch.setattr(sm, "PREFILL_COMMIT_CANCEL_WAIT_S", 0.3) + rig = _rig(tmp_path, mock_tokenizer, split) + try: + phases = [] + + class _Teardown: + def set_phase(self, phase, progress=None): + phases.append((phase, progress)) + + def remaining(self, *, mlx=False): + return 5.0 + + gate, _ = _stuck_final_store(rig, gated, monkeypatch) + rig.scheduler._engine_teardown = _Teardown() + rig.scheduler.shutdown() + waiting = [p for p in phases if p[0] == "prefill_commits"] + assert waiting and callable(waiting[0][1]) + finally: + gate.release.set() + rig.close() From 4ddc6a45bed26740aaeb89435b88ce871fabbcb3 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Mon, 5 Oct 2026 12:46:07 -0600 Subject: [PATCH 16/18] feat(memory): abort one victim instead of all when nothing is parkable 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). --- docs/TESTING.md | 2 + omlx/engine/batched.py | 8 + omlx/engine/vlm.py | 10 ++ omlx/engine_core.py | 199 ++++++++++++++++-------- omlx/process_memory_enforcer.py | 52 +++++++ omlx/request.py | 10 ++ omlx/scheduler.py | 44 +++++- omlx/server.py | 1 + omlx/settings.py | 7 + tests/test_memory_single_victim.py | 214 ++++++++++++++++++++++++++ tests/test_process_memory_enforcer.py | 155 +++++++++++++++++++ tests/test_settings.py | 26 ++++ 12 files changed, 660 insertions(+), 68 deletions(-) create mode 100644 tests/test_memory_single_victim.py diff --git a/docs/TESTING.md b/docs/TESTING.md index 7706308202..d19215d021 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -239,4 +239,6 @@ Mocked tests do not replace hardware validation: with a real model, abort a long Run `python -m pytest -q tests/test_scheduler_park.py tests/test_process_memory_enforcer.py tests/test_settings.py -k "park or Park"` to check `scheduler.memory_pressure_park` (also `OMLX_MEMORY_PRESSURE_PARK`; off by default), `scheduler.max_parks_per_request` (`OMLX_MAX_PARKS_PER_REQUEST`, default 3) and `scheduler.park_resume_ok_polls` (`OMLX_PARK_RESUME_OK_POLLS`, default 3). With the setting on, hard (non-emergency) memory pressure parks the most recent chunked-prefill request instead of aborting: it is re-queued without an error, keeps its stream, and resumes in arrival order after enough consecutive ok pressure polls, restoring the blocks that `prefill_progress_commit_blocks` committed (without it the park resumes cold). The oldest admitted request is protected, parked blocks are pinned against eviction until the resume, and the legacy abort remains for emergency pressure, nothing parkable, an exhausted park budget, or external-loop (non-chunked, VLM) and SpecPrefill prefills, which cannot be parked between steps. The scheduler cases run on a small Qwen3.5 hybrid model and compare a resumed request's output with an uninterrupted run; its prompts must stay below the tiny vocabulary of 32 ids, or the embedding read is undefined and the output is nondeterministic. +Run `python -m pytest -q tests/test_memory_single_victim.py tests/test_process_memory_enforcer.py -k "single or victim"` to check `memory.abort_single_victim` (env `OMLX_MEMORY_ABORT_SINGLE_VICTIM`, default off). On the non-emergency hard path with nothing parkable, the enforcer aborts only the live request holding the most KV (newest arrival on ties), waits for its memory to drain before choosing another, and keeps the rest running. Emergency pressure and model unload still abort everything. Off keeps the abort-all. + Mocked tests do not replace hardware validation: with a real model, run three concurrent long prompts under a ceiling too low for all of them and check that each completes with the park/resume log lines and a cached count close to the last commit, and that no client sees a memory error. diff --git a/omlx/engine/batched.py b/omlx/engine/batched.py index aaef48d678..646c89ac62 100644 --- a/omlx/engine/batched.py +++ b/omlx/engine/batched.py @@ -1573,6 +1573,14 @@ def get_cache_stats(self) -> dict[str, Any] | None: return self._engine.get_cache_stats() return None + async def abort_one_request_for_memory(self, *, spare_parked: bool = True): + """Abort the single request that frees the most memory, or None.""" + if self._engine and self._engine.engine: + return await self._engine.engine.abort_one_request_for_memory( + spare_parked=spare_parked + ) + return None + async def abort_all_requests( self, *, diff --git a/omlx/engine/vlm.py b/omlx/engine/vlm.py index 0c1d3e84ad..9b99f1d57c 100644 --- a/omlx/engine/vlm.py +++ b/omlx/engine/vlm.py @@ -6019,6 +6019,16 @@ def get_cache_stats(self) -> dict[str, Any] | None: return self._engine.get_cache_stats() return None + async def abort_one_request_for_memory(self, *, spare_parked: bool = True): + """Abort the single request that frees the most memory, or None.""" + if self.is_diffusion_model: + return None + if self._engine and self._engine.engine: + return await self._engine.engine.abort_one_request_for_memory( + spare_parked=spare_parked + ) + return None + async def abort_all_requests( self, *, diff --git a/omlx/engine_core.py b/omlx/engine_core.py index ff18d94479..5304057e08 100644 --- a/omlx/engine_core.py +++ b/omlx/engine_core.py @@ -44,7 +44,7 @@ ) from .model_registry import get_registry from .output_collector import RequestOutputCollector, RequestStreamState -from .request import Request, RequestOutput, SamplingParams +from .request import MemoryVictim, Request, RequestOutput, SamplingParams from .scheduler import Scheduler, SchedulerConfig, _sync_and_clear_cache from .utils.fatal import ( FATAL_TEARDOWN_TIMEOUT_S, @@ -842,8 +842,6 @@ async def abort_all_requests( every unload, eviction, emergency or shutdown path must abort them, or they are orphaned (or block the unload from ever draining). """ - from .utils.proc_memory import get_phys_footprint - # Only abort requests not already finished or pending abort. The # enforcer calls this once per poll (1s) while pressure persists; a # deferred abort can take many seconds to drain (it executes at the @@ -869,6 +867,53 @@ async def abort_all_requests( and rid not in pending_aborts and not (spare_parked and callable(is_parked) and is_parked(rid) is True) ] + ctx = self._memory_abort_context(reason) + for rid in request_ids: + self.scheduler.abort_request(rid) + self._emit_memory_abort(rid, ctx, reason, error_code) + self._mark_request_finished(rid) + if request_ids: + if reason is None: + logger.warning( + f"Aborted {len(request_ids)} requests due to memory pressure" + ) + else: + logger.warning("Aborted %d requests: %s", len(request_ids), reason) + self._wake_engine_loop() + return len(request_ids) + + async def abort_one_request_for_memory( + self, *, spare_parked: bool = True + ) -> MemoryVictim | None: + """Abort the single live request that frees the most memory. + + The victim is chosen by the scheduler (largest live KV, newest arrival + on ties) and receives the same error frame ``abort_all_requests`` + sends under memory pressure; every other request keeps running. + Returns the victim, or None when nothing live can be aborted. + """ + sched = self.scheduler + select = getattr(sched, "select_memory_victim", None) + if sched is None or not callable(select): + return None + victim = select(spare_parked=spare_parked) + if victim is None: + return None + rid = victim.request_id + # Only a request with a client attached (and not already finished) is + # worth aborting: otherwise the abort frees nothing observable. + if rid not in self._output_collectors or rid in self._finished_at: + return None + sched.abort_request(rid) + self._emit_memory_abort(rid, self._memory_abort_context(None), None, None) + self._mark_request_finished(rid) + self._wake_engine_loop() + return victim + + def _memory_abort_context(self, reason: str | None) -> dict[str, Any]: + """Measured usage, limits and advice behind a memory-pressure abort.""" + from .utils.proc_memory import get_phys_footprint + ceiling = 0 watermark = 0 sched = self.scheduler @@ -898,73 +943,84 @@ async def abort_all_requests( ) advice = f"{advice}." ceiling_label = f"{binding} ceiling" if binding != "effective" else "ceiling" - for rid in request_ids: - self.scheduler.abort_request(rid) - collector = self._output_collectors.get(rid) - if collector is not None: - # Name the watermark that actually tripped; printing only the - # ceiling reads as "usage below limit yet aborted" (#2321). - if reason is not None: - error_msg = reason - elif watermark > 0 and ceiling > 0: - error_msg = ( - f"Request aborted: process memory limit exceeded " - f"(usage {usage_gb:.1f} GB, abort threshold " - f"(hard watermark) {watermark_gb:.1f} GB, " - f"{ceiling_label} {ceiling_gb:.1f} GB). " - f"{advice}" - ) - elif ceiling > 0: - error_msg = ( - f"Request aborted: process memory limit exceeded " - f"(usage {usage_gb:.1f} GB, " - f"{ceiling_label} {ceiling_gb:.1f} GB). " - f"{advice}" - ) - else: - error_msg = ( - f"Request aborted: process memory limit exceeded " - f"(usage {usage_gb:.1f} GB). " - f"{advice}" - ) - collector.put( - RequestOutput( - request_id=rid, - finished=True, - finish_reason="error", - new_text=f"\n\n[Error: {error_msg}]", - error=error_msg, - # Without a code this surfaced as a bare RuntimeError: - # the JSON keepalive wrapper never saw a memory error, - # so the response generator died mid-body and the - # client got a truncated read plus a 500 traceback - # instead of the same actionable 400 the pre-flight - # guard returns. - error_code=error_code or "prefill_memory_aborted", - error_metadata={ - "request_id": rid, - # Only the limit is reported: the exception's - # estimated_bytes means "predicted peak", and this - # abort fires on measured usage, which the message - # already states. - "limit_bytes": ( - watermark or ceiling or None - if reason is None - else None - ), - }, - ) + return { + "usage_gb": usage_gb, + "ceiling": ceiling, + "watermark": watermark, + "ceiling_gb": ceiling_gb, + "watermark_gb": watermark_gb, + "ceiling_label": ceiling_label, + "advice": advice, + } + + def _emit_memory_abort( + self, + rid: str, + ctx: dict[str, Any], + reason: str | None, + error_code: str | None, + ) -> None: + """Send the memory-abort error frame to ``rid``'s consumer.""" + usage_gb = ctx["usage_gb"] + ceiling = ctx["ceiling"] + watermark = ctx["watermark"] + ceiling_gb = ctx["ceiling_gb"] + watermark_gb = ctx["watermark_gb"] + ceiling_label = ctx["ceiling_label"] + advice = ctx["advice"] + collector = self._output_collectors.get(rid) + if collector is not None: + # Name the watermark that actually tripped; printing only the + # ceiling reads as "usage below limit yet aborted" (#2321). + if reason is not None: + error_msg = reason + elif watermark > 0 and ceiling > 0: + error_msg = ( + f"Request aborted: process memory limit exceeded " + f"(usage {usage_gb:.1f} GB, abort threshold " + f"(hard watermark) {watermark_gb:.1f} GB, " + f"{ceiling_label} {ceiling_gb:.1f} GB). " + f"{advice}" ) - self._mark_request_finished(rid) - if request_ids: - if reason is None: - logger.warning( - f"Aborted {len(request_ids)} requests due to memory pressure" + elif ceiling > 0: + error_msg = ( + f"Request aborted: process memory limit exceeded " + f"(usage {usage_gb:.1f} GB, " + f"{ceiling_label} {ceiling_gb:.1f} GB). " + f"{advice}" ) else: - logger.warning("Aborted %d requests: %s", len(request_ids), reason) - self._wake_engine_loop() - return len(request_ids) + error_msg = ( + f"Request aborted: process memory limit exceeded " + f"(usage {usage_gb:.1f} GB). " + f"{advice}" + ) + collector.put( + RequestOutput( + request_id=rid, + finished=True, + finish_reason="error", + new_text=f"\n\n[Error: {error_msg}]", + error=error_msg, + # Without a code this surfaced as a bare RuntimeError: + # the JSON keepalive wrapper never saw a memory error, + # so the response generator died mid-body and the + # client got a truncated read plus a 500 traceback + # instead of the same actionable 400 the pre-flight + # guard returns. + error_code=error_code or "prefill_memory_aborted", + error_metadata={ + "request_id": rid, + # Only the limit is reported: the exception's + # estimated_bytes means "predicted peak", and this + # abort fires on measured usage, which the message + # already states. + "limit_bytes": ( + watermark or ceiling or None if reason is None else None + ), + }, + ) + ) def _mark_request_finished(self, request_id: str) -> None: """Signal the consumer a request finished and stamp the finish time. @@ -1482,6 +1538,15 @@ async def abort_request(self, request_id: str) -> bool: return False return await engine.abort_request(request_id) + async def abort_one_request_for_memory( + self, *, spare_parked: bool = True + ) -> MemoryVictim | None: + """Abort the single request that frees the most memory.""" + engine = getattr(self, "engine", None) + if engine is None: + return None + return await engine.abort_one_request_for_memory(spare_parked=spare_parked) + async def abort_all_requests( self, *, diff --git a/omlx/process_memory_enforcer.py b/omlx/process_memory_enforcer.py index 32ecf83c61..f4646146b7 100644 --- a/omlx/process_memory_enforcer.py +++ b/omlx/process_memory_enforcer.py @@ -401,6 +401,7 @@ def __init__( hard_threshold: float | None = None, prefill_safe_zone_ratio: float = 0.89, prefill_min_chunk_tokens: int = 256, + abort_single_victim: bool = False, ): """ Initialize the process memory enforcer. @@ -430,6 +431,8 @@ def __init__( prefill_safe_zone_ratio: Fraction of hard cap below which prefill runs at full chunk size; above triggers adaptive shrink. prefill_min_chunk_tokens: Floor for adaptive shrink. + abort_single_victim: On the non-emergency hard path with nothing + parkable, abort one victim instead of every request. """ self._engine_pool = engine_pool self._memory_guard_tier = self._normalize_tier(memory_guard_tier) @@ -454,6 +457,7 @@ def __init__( self._prefill_headroom_safety = self._get_prefill_headroom_safety() self._prefill_safe_zone_ratio = prefill_safe_zone_ratio self._prefill_min_chunk_tokens = prefill_min_chunk_tokens + self._single_victim_on = bool(abort_single_victim) self._task: asyncio.Task | None = None self._loop: asyncio.AbstractEventLoop | None = None self._wake_event: asyncio.Event | None = None @@ -1586,6 +1590,40 @@ async def _abort_all_requests(engine: Any, *, spare_parked: bool) -> Any: except TypeError: return await engine.abort_all_requests() + def _abort_single_victim_enabled(self) -> bool: + """``memory.abort_single_victim`` (default off). + + Off keeps the legacy abort-all on the non-emergency hard path. + """ + return self._single_victim_on + + async def _abort_single_victim(self, engine: Any, model_id: str) -> Any: + """Abort the one request freeing the most memory; None means fall back. + + Returns None when the switch is off, the engine has no such hook, or + no live request can be chosen, so the caller aborts everything as + before. At most one victim per call, so the next poll re-measures + before another request is sacrificed. + """ + if not self._abort_single_victim_enabled(): + return None + abort_one = getattr(engine, "abort_one_request_for_memory", None) + if not callable(abort_one): + return None + victim = await abort_one(spare_parked=True) + if victim is None: + return None + logger.warning( + "Hard memory pressure: aborted 1 victim %s (%d tokens, ~%.1f GB) " + "on '%s'; %d request(s) kept", + victim.request_id, + victim.tokens, + victim.est_bytes / 1024**3, + model_id, + victim.kept, + ) + return victim + async def _abort_loaded_requests_for_memory_emergency(self) -> int: """Abort active requests on loaded models without unloading them.""" aborted_total = 0 @@ -1961,6 +1999,20 @@ async def _check_and_enforce(self) -> None: # loaded and lets parked requests resume; an # emergency unload must abort them, or they keep # the engine non-idle and the unload never drains. + # Deliberate safety brake: only the non-emergency + # hard path narrows to one victim. The emergency + # path (beyond the ceiling) and model unload keep + # abort-all, since a half-measure there risks the + # process being killed for memory. + single = ( + None + if emergency + else await self._abort_single_victim( + entry.engine, busy_victim + ) + ) + if single is not None: + break aborted = await self._abort_all_requests( entry.engine, spare_parked=not emergency ) diff --git a/omlx/request.py b/omlx/request.py index adfa77c4c4..62b21ac702 100644 --- a/omlx/request.py +++ b/omlx/request.py @@ -95,6 +95,16 @@ def __post_init__(self): self.stop_token_ids = [] +@dataclass(frozen=True) +class MemoryVictim: + """The one request a memory-pressure abort chose, and what it held.""" + + request_id: str + tokens: int # live KV tokens (prompt + generated, or prefilled so far) + est_bytes: int # estimated KV bytes freed (0 when no estimator is wired) + kept: int # live requests left running + + @dataclass class Request: """ diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 6c7d545121..042b5cce3c 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -80,7 +80,13 @@ from .prefill_commit_executor import DaemonCommitExecutor as _DaemonCommitExecutor from .prefill_progress import get_prefill_tracker from .prefill_transient_tracker import PrefillTransientTracker -from .request import Request, RequestOutput, RequestStatus, SamplingParams +from .request import ( + MemoryVictim, + Request, + RequestOutput, + RequestStatus, + SamplingParams, +) from .speculative.processing_sampler import ( MTPProcessingSampler, MTPProcessorContractError, @@ -12037,6 +12043,42 @@ def _park_hold_applies(self, head: "Request") -> bool: return self._polls_since_resume < need return True + def select_memory_victim(self, *, spare_parked: bool = True) -> MemoryVictim | None: + """Pick the one live request whose abort frees the most memory. + + Largest live KV footprint first (a decoding request holds prompt plus + generated tokens, a chunked prefill what it has computed so far); the + most recent arrival breaks ties, since it has lost the least work. + Parked requests hold no live memory and are spared by default, as are + queued requests with no KV and requests already pending an abort. + Returns None when nothing live can be chosen. Read-only: the caller + aborts the victim. + """ + pending = set(self._pending_abort_ids) + prefilling_ids = {r.request_id for r in self.prefilling} + live: list[tuple[int, float, str]] = [] + for rid, request in list(self.requests.items()): + if rid in pending: + continue + if spare_parked and self.is_request_parked(rid): + continue + if rid in self.running: + tokens = request.num_tokens + elif rid in prefilling_ids or rid in self._prefill_states: + tokens = request.num_computed_tokens + else: + continue + if tokens > 0: + live.append((tokens, request.arrival_time, rid)) + if not live: + return None + tokens, _, rid = max(live, key=lambda item: (item[0], item[1])) + monitor = self.memory_monitor + est_bytes = ( + int(monitor.estimate_prompt_kv_bytes(tokens)) if monitor is not None else 0 + ) + return MemoryVictim(rid, tokens, est_bytes, kept=len(live) - 1) + def is_request_parked(self, request_id: str) -> bool: """Whether the request is currently parked (holds no live memory).""" request = self.requests.get(request_id) diff --git a/omlx/server.py b/omlx/server.py index ee0aacea6e..ce05e4a098 100644 --- a/omlx/server.py +++ b/omlx/server.py @@ -595,6 +595,7 @@ async def _bonjour_supervisor() -> None: hard_threshold=memory_settings.hard_threshold, prefill_safe_zone_ratio=memory_settings.prefill_safe_zone_ratio, prefill_min_chunk_tokens=memory_settings.prefill_min_chunk_tokens, + abort_single_victim=memory_settings.abort_single_victim, ) _server_state.process_memory_enforcer = enforcer _server_state.engine_pool._process_memory_enforcer = enforcer diff --git a/omlx/settings.py b/omlx/settings.py index b468b08366..0441bc7a84 100644 --- a/omlx/settings.py +++ b/omlx/settings.py @@ -611,6 +611,9 @@ class MemorySettings: # aborted via the same cleanup path the hard-limit RuntimeError uses. prefill_safe_zone_ratio: float = 0.80 prefill_min_chunk_tokens: int = 32 + # On the non-emergency hard path with nothing parkable, abort only the + # live request holding the most KV instead of every request. + abort_single_victim: bool = False def to_dict(self) -> dict[str, Any]: """Convert to dictionary.""" @@ -622,6 +625,7 @@ def to_dict(self) -> dict[str, Any]: "hard_threshold": self.hard_threshold, "prefill_safe_zone_ratio": self.prefill_safe_zone_ratio, "prefill_min_chunk_tokens": self.prefill_min_chunk_tokens, + "abort_single_victim": self.abort_single_victim, } @classmethod @@ -640,6 +644,7 @@ def from_dict(cls, data: dict[str, Any]) -> MemorySettings: hard_threshold=float(data.get("hard_threshold", 0.95)), prefill_safe_zone_ratio=float(data.get("prefill_safe_zone_ratio", 0.80)), prefill_min_chunk_tokens=int(data.get("prefill_min_chunk_tokens", 32)), + abort_single_victim=data.get("abort_single_victim") is True, ) @@ -1299,6 +1304,8 @@ def _apply_env_overrides(self) -> None: f"Invalid OMLX_PREFILL_PROGRESS_COMMIT_BLOCKS value: " f"{commit_blocks}" ) + if single := os.getenv("OMLX_MEMORY_ABORT_SINGLE_VICTIM"): + self.memory.abort_single_victim = single.lower() in ("true", "1", "yes") if park := os.getenv("OMLX_MEMORY_PRESSURE_PARK"): self.scheduler.memory_pressure_park = park.lower() in ("true", "1", "yes") for env_name, attr in ( diff --git a/tests/test_memory_single_victim.py b/tests/test_memory_single_victim.py new file mode 100644 index 0000000000..baf34c20b3 --- /dev/null +++ b/tests/test_memory_single_victim.py @@ -0,0 +1,214 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Single-victim memory abort: pick one request instead of aborting them all. + +Covers the scheduler's victim choice (largest live KV, newest arrival breaks +ties, parked and KV-less requests never chosen) and the engine's abort of that +one request, which must hand its client the same error frame as the abort-all +path. +""" + +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import pytest + +from omlx.engine_core import EngineCore +from omlx.request import MemoryVictim, Request, RequestStatus, SamplingParams +from omlx.scheduler import Scheduler + +GB = 1024**3 + + +def _req(rid, prompt_tokens, output_tokens=0, arrival=0.0, parked=False): + request = Request( + request_id=rid, + prompt=[1] * prompt_tokens, + sampling_params=SamplingParams(max_tokens=64), + arrival_time=arrival, + ) + request.num_prompt_tokens = prompt_tokens + request.output_token_ids = [2] * output_tokens + request.num_computed_tokens = prompt_tokens + output_tokens + request.status = RequestStatus.RUNNING + request.parked = parked + return request + + +def _fake_scheduler(running=(), prefilling=(), waiting=(), pending=(), monitor=None): + """The attributes ``Scheduler.select_memory_victim`` reads.""" + everything = [*running, *prefilling, *waiting] + fake = SimpleNamespace( + requests={r.request_id: r for r in everything}, + running={r.request_id: r for r in running}, + prefilling=list(prefilling), + waiting=list(waiting), + _pending_abort_ids=set(pending), + _prefill_states={r.request_id: object() for r in prefilling}, + memory_monitor=monitor, + ) + fake.is_request_parked = lambda rid: bool(fake.requests[rid].parked) + return fake + + +def _select(fake, **kwargs): + return Scheduler.select_memory_victim(fake, **kwargs) + + +class TestSelectMemoryVictim: + def test_largest_live_kv_is_chosen_among_three_decoding_requests(self): + fake = _fake_scheduler( + running=[ + _req("small", 1_000, 10, arrival=1.0), + _req("big", 90_000, 500, arrival=2.0), + _req("mid", 30_000, 200, arrival=3.0), + ] + ) + + victim = _select(fake) + + assert victim.request_id == "big" + assert victim.tokens == 90_500 + assert victim.kept == 2 + + def test_tie_goes_to_the_most_recent_arrival(self): + fake = _fake_scheduler( + running=[ + _req("old", 5_000, 0, arrival=1.0), + _req("new", 5_000, 0, arrival=9.0), + _req("mid", 5_000, 0, arrival=4.0), + ] + ) + + assert _select(fake).request_id == "new" + + def test_a_prefilling_request_counts_by_computed_tokens(self): + prefill = _req("pf", 200_000, 0, arrival=2.0) + prefill.num_computed_tokens = 120_000 + fake = _fake_scheduler( + running=[_req("dec", 50_000, 100, arrival=1.0)], prefilling=[prefill] + ) + + victim = _select(fake) + + assert victim.request_id == "pf" + assert victim.tokens == 120_000 + + def test_parked_requests_are_never_chosen(self): + fake = _fake_scheduler( + running=[_req("live", 1_000, 0, arrival=1.0)], + waiting=[_req("parked", 150_000, 0, arrival=2.0, parked=True)], + ) + + assert _select(fake).request_id == "live" + + def test_requests_without_live_kv_are_never_chosen(self): + waiting = _req("queued", 10_000, 0, arrival=5.0) + waiting.num_computed_tokens = 0 + fake = _fake_scheduler(waiting=[waiting]) + + assert _select(fake) is None + + def test_a_request_with_a_pending_abort_is_skipped(self): + fake = _fake_scheduler( + running=[ + _req("gone", 90_000, 0, arrival=1.0), + _req("live", 1_000, 0, arrival=2.0), + ], + pending={"gone"}, + ) + + victim = _select(fake) + + assert victim.request_id == "live" + assert victim.kept == 0 + + def test_estimated_bytes_use_the_kv_estimator_when_available(self): + monitor = SimpleNamespace(estimate_prompt_kv_bytes=lambda n: n * 1000.0) + fake = _fake_scheduler(running=[_req("a", 2_000, 0)], monitor=monitor) + + assert _select(fake).est_bytes == 2_000_000 + + +def _engine(scheduler, collectors): + engine = object.__new__(EngineCore) + engine.scheduler = scheduler + engine._output_collectors = collectors + engine._finished_at = {} + engine._finished_events = {} + engine._closed = False + engine._mark_request_finished = lambda rid: engine._finished_at.setdefault(rid, 1.0) + engine._wake_engine_loop = lambda: None + return engine + + +def _scheduler_for_engine(victim_rid, kept=2): + sched = MagicMock() + sched._pending_abort_ids = set() + sched._memory_hard_limit_bytes = 100 * GB + sched._memory_hard_watermark_bytes = 95 * GB + sched.is_request_parked.return_value = False + sched.select_memory_victim.return_value = ( + None + if victim_rid is None + else MemoryVictim(victim_rid, tokens=90_000, est_bytes=6 * GB, kept=kept) + ) + return sched + + +class TestEngineAbortOneRequestForMemory: + @pytest.mark.asyncio + async def test_only_the_victim_is_aborted_and_the_others_keep_running(self): + sched = _scheduler_for_engine("big") + collectors = {rid: MagicMock() for rid in ("big", "b", "c")} + engine = _engine(sched, collectors) + + with patch("omlx.utils.proc_memory.get_phys_footprint", return_value=97 * GB): + victim = await engine.abort_one_request_for_memory() + + assert victim.request_id == "big" + sched.abort_request.assert_called_once_with("big") + collectors["big"].put.assert_called_once() + collectors["b"].put.assert_not_called() + collectors["c"].put.assert_not_called() + assert set(engine._finished_at) == {"big"} + + @pytest.mark.asyncio + async def test_victim_gets_the_same_error_frame_as_abort_all(self): + with patch("omlx.utils.proc_memory.get_phys_footprint", return_value=97 * GB): + one_sched = _scheduler_for_engine("r") + one = {"r": MagicMock()} + await _engine(one_sched, one).abort_one_request_for_memory() + + all_sched = _scheduler_for_engine(None) + all_sched._pending_abort_ids = set() + every = {"r": MagicMock()} + await _engine(all_sched, every).abort_all_requests() + + single = one["r"].put.call_args.args[0] + legacy = every["r"].put.call_args.args[0] + assert single.finished is True + assert single.finish_reason == legacy.finish_reason == "error" + assert single.error_code == legacy.error_code == "prefill_memory_aborted" + assert single.error == legacy.error + assert "process memory limit exceeded" in single.error + assert single.new_text == legacy.new_text + assert single.error_metadata == legacy.error_metadata + + @pytest.mark.asyncio + async def test_no_victim_aborts_nothing_and_returns_none(self): + sched = _scheduler_for_engine(None) + collectors = {"a": MagicMock()} + engine = _engine(sched, collectors) + + assert await engine.abort_one_request_for_memory() is None + + sched.abort_request.assert_not_called() + collectors["a"].put.assert_not_called() + + @pytest.mark.asyncio + async def test_a_victim_without_a_collector_is_not_reported(self): + sched = _scheduler_for_engine("ghost") + engine = _engine(sched, {"other": MagicMock()}) + + assert await engine.abort_one_request_for_memory() is None + sched.abort_request.assert_not_called() diff --git a/tests/test_process_memory_enforcer.py b/tests/test_process_memory_enforcer.py index 244ce287f2..baee873477 100644 --- a/tests/test_process_memory_enforcer.py +++ b/tests/test_process_memory_enforcer.py @@ -3600,3 +3600,158 @@ async def test_every_poll_reports_its_level_to_the_scheduler(self, enforcer): await self._tick(enforcer, usage=96 * 1024**3) scheduler.note_pressure_poll.assert_called_with("hard") assert scheduler.note_pressure_poll.call_count == 2 + + +class TestSingleVictimFallback: + """Hard pressure with nothing parkable aborts one victim, not every request. + + The emergency path (beyond the ceiling) and model unload keep abort-all as + a deliberate safety brake. ``memory.abort_single_victim`` off restores + the legacy abort-all on the hard path. + """ + + @pytest.fixture + def enforcer(self, mock_engine_pool): + # Hard watermark (95 GB) below the ceiling (100 GB): hard is not + # emergency until usage passes the ceiling by the emergency margin. + return _make_enforcer( + mock_engine_pool, + ceiling=100 * 1024**3, + soft_threshold=0.85, + hard_threshold=0.95, + ) + + @staticmethod + def _engine(victims): + from omlx.request import MemoryVictim + + engine = MagicMock() + engine.has_active_requests.return_value = False + engine.abort_all_requests = AsyncMock(return_value=3) + engine.abort_one_request_for_memory = AsyncMock( + side_effect=[ + MemoryVictim(rid, 90_000, 6 * 1024**3, kept) for rid, kept in victims + ] + + [None] + ) + return engine + + @staticmethod + def _busy(enforcer, engine): + entry = _make_entry("big-model", engine=engine) + entry.in_use = 1 + enforcer._engine_pool._entries = {"big-model": entry} + enforcer._engine_pool._find_lru_victim.return_value = None + return entry + + @staticmethod + async def _tick(enforcer, usage_gb): + with patch("omlx.process_memory_enforcer.mx") as mock_mx: + mock_mx.get_active_memory.side_effect = _cycling([usage_gb * 1024**3]) + await enforcer._check_and_enforce() + + @pytest.mark.asyncio + async def test_hard_pressure_aborts_exactly_one_victim( + self, enforcer, monkeypatch, caplog + ): + enforcer._single_victim_on = True + engine = self._engine([("req-big", 2)]) + entry = self._busy(enforcer, engine) + + with caplog.at_level("WARNING"): + await self._tick(enforcer, 97) + + engine.abort_one_request_for_memory.assert_awaited_once_with(spare_parked=True) + engine.abort_all_requests.assert_not_awaited() + assert entry.engine is engine + assert entry.pending_unload_reason is None + assert "aborted 1 victim req-big (90000 tokens" in caplog.text + assert "2 request(s) kept" in caplog.text + assert "'big-model'" in caplog.text + + @pytest.mark.asyncio + async def test_persisting_pressure_aborts_one_more_victim_per_poll( + self, enforcer, monkeypatch + ): + enforcer._single_victim_on = True + engine = self._engine([("first", 2), ("second", 1)]) + self._busy(enforcer, engine) + + await self._tick(enforcer, 97) + assert engine.abort_one_request_for_memory.await_count == 1 + + await self._tick(enforcer, 97) + assert engine.abort_one_request_for_memory.await_count == 2 + engine.abort_all_requests.assert_not_awaited() + + @pytest.mark.asyncio + async def test_recovered_pressure_aborts_no_second_victim( + self, enforcer, monkeypatch + ): + enforcer._single_victim_on = True + engine = self._engine([("first", 2), ("second", 1)]) + self._busy(enforcer, engine) + + await self._tick(enforcer, 97) + await self._tick(enforcer, 1) + + assert engine.abort_one_request_for_memory.await_count == 1 + + @pytest.mark.asyncio + async def test_emergency_still_aborts_everything(self, enforcer, monkeypatch): + enforcer._single_victim_on = True + engine = self._engine([("req-big", 2)]) + entry = self._busy(enforcer, engine) + + await self._tick(enforcer, 103) + + engine.abort_all_requests.assert_awaited_once_with(spare_parked=False) + engine.abort_one_request_for_memory.assert_not_awaited() + assert entry.pending_unload_reason == "hard memory pressure" + + @pytest.mark.asyncio + async def test_flag_off_keeps_the_legacy_abort_all(self, enforcer, monkeypatch): + enforcer._single_victim_on = False + engine = self._engine([("req-big", 2)]) + self._busy(enforcer, engine) + + await self._tick(enforcer, 97) + + engine.abort_all_requests.assert_awaited_once_with(spare_parked=True) + engine.abort_one_request_for_memory.assert_not_awaited() + + @pytest.mark.asyncio + async def test_flag_unset_keeps_the_legacy_abort_all(self, enforcer, monkeypatch): + engine = self._engine([("req-big", 2)]) + self._busy(enforcer, engine) + + await self._tick(enforcer, 97) + + engine.abort_all_requests.assert_awaited_once() + engine.abort_one_request_for_memory.assert_not_awaited() + + @pytest.mark.asyncio + async def test_no_victim_falls_back_to_abort_all_sparing_parked( + self, enforcer, monkeypatch + ): + enforcer._single_victim_on = True + engine = self._engine([]) + self._busy(enforcer, engine) + + await self._tick(enforcer, 97) + + engine.abort_one_request_for_memory.assert_awaited_once() + engine.abort_all_requests.assert_awaited_once_with(spare_parked=True) + + @pytest.mark.asyncio + async def test_engine_without_the_hook_falls_back_to_abort_all( + self, enforcer, monkeypatch + ): + enforcer._single_victim_on = True + engine = _ParkedOnlyEngine() + self._busy(enforcer, engine) + + with patch.object(enforcer, "_current_usage_bytes", return_value=97 * 1024**3): + await enforcer._check_and_enforce() + + assert engine.calls == [True] diff --git a/tests/test_settings.py b/tests/test_settings.py index 5def31bfa6..4ce0c57f06 100644 --- a/tests/test_settings.py +++ b/tests/test_settings.py @@ -3358,3 +3358,29 @@ def test_inference_opt_in_keeps_network_management_requirements( allow_unauthenticated_inference=True, ) assert any("non-loopback" in error for error in settings.validate()) + + +class TestAbortSingleVictimSetting: + """memory.abort_single_victim: off by default, round-trips, env override.""" + + def test_defaults_off_and_round_trips(self): + assert MemorySettings.from_dict({}).abort_single_victim is False + on = MemorySettings.from_dict({"abort_single_victim": True}) + assert on.abort_single_victim is True + assert on.to_dict()["abort_single_victim"] is True + junk = MemorySettings.from_dict({"abort_single_victim": "yes"}) + assert junk.abort_single_victim is False + + def test_env_override(self, tmp_path): + env = {"OMLX_MEMORY_ABORT_SINGLE_VICTIM": "true"} + with patch.dict(os.environ, env, clear=False): + settings = GlobalSettings.load(base_path=tmp_path) + assert settings.memory.abort_single_victim is True + + def test_reaches_the_enforcer(self): + from omlx.process_memory_enforcer import ProcessMemoryEnforcer + + default = ProcessMemoryEnforcer(engine_pool=MagicMock()) + assert default._abort_single_victim_enabled() is False + on = ProcessMemoryEnforcer(engine_pool=MagicMock(), abort_single_victim=True) + assert on._abort_single_victim_enabled() is True From 4b30e60c3d57756951e87b70b284846ae07b0a2e Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Mon, 5 Oct 2026 13:52:05 -0600 Subject: [PATCH 17/18] feat(cache): domain-isolated exact-prefix chains and exact-chain pins 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. --- omlx/cache/prefix_cache.py | 88 ++++++++++++++++++++++++++++-------- omlx/scheduler.py | 41 ++++++++++++++--- tests/test_prefix_cache.py | 79 ++++++++++++++++++++++++++++++++ tests/test_scheduler_park.py | 74 ++++++++++++++++++++++++++++++ 4 files changed, 257 insertions(+), 25 deletions(-) diff --git a/omlx/cache/prefix_cache.py b/omlx/cache/prefix_cache.py index d4f9c8e5c4..695e91b693 100644 --- a/omlx/cache/prefix_cache.py +++ b/omlx/cache/prefix_cache.py @@ -196,6 +196,30 @@ def _wrap_cachelist_sub_marker( _EXACT_PREFIX_TERMINAL_KEY = "specprefill-static-exact-v1" _EXACT_PREFIX_SPLIT_BLOCK_KEY = "specprefill-static-exact-split-v1" +# Exact chains stored under a caller domain (for example one request's paused +# decode) carry the domain in every block hash, so two requests with identical +# tokens never share or overwrite each other's chain, and none of its blocks +# enter ordinary prefix matching. +_EXACT_PREFIX_DOMAIN_KEY = "exact-prefix-domain-v1" + + +def _exact_block_extra_keys( + *, + terminal: bool, + split_gdn_layout: bool, + domain_key: tuple[str, ...] | None, +) -> tuple[Any, ...] | None: + """Hash extra keys of one exact-prefix block (store and fetch agree).""" + if domain_key is not None: + domain = (_EXACT_PREFIX_DOMAIN_KEY, *domain_key) + return (*domain, _EXACT_PREFIX_TERMINAL_KEY) if terminal else domain + if split_gdn_layout: + return (_EXACT_PREFIX_SPLIT_BLOCK_KEY,) + if terminal: + return (_EXACT_PREFIX_TERMINAL_KEY,) + return None + + _POOLING_CACHE_SUB_CLASSES = frozenset({"PoolingCache", "BatchPoolingCache"}) # Sentinel: the CacheList restore chain carries no PoolingCacheDelta # markers, so the caller restores the boundary member last-block-wins. @@ -900,6 +924,7 @@ def store_cache( _store_exact_terminal: bool = False, _store_tail_terminal: bool = False, cache_covers_suffix_only: bool = False, + _exact_domain_key: tuple[str, ...] | None = None, ) -> BlockTable | None: """ Store computed cache for future reuse. @@ -932,6 +957,8 @@ def store_cache( commit during prefill), never the whole sequence. Without this a window longer than the stored prefix is indistinguishable from a full-sequence cache. + _exact_domain_key: Exact-prefix mode only: isolate the whole + chain under this caller domain (see store_exact_prefix). Returns: BlockTable for the stored cache, or None on failure @@ -1194,19 +1221,26 @@ def store_cache( is_exact_split_block = _store_exact_terminal and split_gdn_layout is_exact_terminal = _store_exact_terminal and i == num_new_blocks - 1 + # A domain-isolated exact chain is reachable only through + # fetch_exact_prefix(): no dedup, no ordinary prefix index. + is_exact_domain_block = ( + _store_exact_terminal and _exact_domain_key is not None + ) is_tail_terminal = ( _store_tail_terminal and i == num_new_blocks - 1 and len(block_tokens) < self.block_size ) block_extra_keys: tuple[Any, ...] | None - if is_exact_split_block: - # Isolate the whole chain. Intermediate split-GDN exact-prefix - # blocks carry structural recurrent placeholders and must never - # enter ordinary partial-prefix matching. - block_extra_keys = (_EXACT_PREFIX_SPLIT_BLOCK_KEY,) - elif is_exact_terminal: - block_extra_keys = (_EXACT_PREFIX_TERMINAL_KEY,) + if is_exact_split_block or is_exact_terminal or is_exact_domain_block: + # Split-GDN exact chains are isolated as a whole: their + # intermediate blocks carry structural recurrent placeholders + # and must never enter ordinary partial-prefix matching. + block_extra_keys = _exact_block_extra_keys( + terminal=is_exact_terminal, + split_gdn_layout=split_gdn_layout, + domain_key=_exact_domain_key, + ) else: block_extra_keys = resolve_block_extra_keys( global_end, @@ -1217,7 +1251,7 @@ def store_cache( # Check if this block already exists (deduplication) if (len(block_tokens) == self.block_size or is_tail_terminal) and not ( - is_exact_terminal or is_exact_split_block + is_exact_terminal or is_exact_split_block or is_exact_domain_block ): existing_block = self.paged_cache.find_cached_block( block_tokens, @@ -1339,12 +1373,16 @@ def store_cache( len(block_tokens) == self.block_size and not is_exact_terminal and not is_exact_split_block + and not is_exact_domain_block ): self.paged_cache.register_block_hash( block, block_tokens, parent_hash, extra_keys=block_extra_keys ) elif ( - is_exact_terminal or is_exact_split_block or is_tail_terminal + is_exact_terminal + or is_exact_split_block + or is_exact_domain_block + or is_tail_terminal ) and block.block_hash is not None: # Tail blocks join the parent-keyed tail index once saved. self.paged_cache.cached_block_hash_to_block.insert( @@ -1697,6 +1735,8 @@ def store_exact_prefix( tokens: list[int], cache_data: list[Any], model_cache_config: ModelCacheConfig | None = None, + *, + domain_key: tuple[str, ...] | None = None, ) -> BlockTable | None: """Persist a complete prefix, including its exact terminal boundary. @@ -1705,6 +1745,12 @@ def store_exact_prefix( never the only durable copy. Split-GDN layouts domain-separate the whole chain and store one recurrent sidecar at the exact terminal; preceding blocks contain only KV slices and structural recurrent placeholders. + + ``domain_key`` (strings) isolates the whole chain: only a fetch with + the same domain finds it, so requests with identical tokens (or + identical image placeholder tokens over different images) never + collide. The returned table's blocks are unreferenced; a caller that + must keep the chain takes its own block refs and SSD pins. """ if not tokens or self.paged_ssd_cache is None: return None @@ -1749,6 +1795,7 @@ def store_exact_prefix( model_cache_config=model_cache_config, hot_cache_write_back=False, _store_exact_terminal=True, + _exact_domain_key=domain_key, ) if block_table is None or block_table.num_tokens != len(tokens): self.paged_cache.delete_block_table(request_id) @@ -1765,7 +1812,11 @@ def store_exact_prefix( self._exact_prefix_stores += 1 return stored_table - def _exact_prefix_hashes(self, tokens: list[int]) -> list[tuple[BlockHash, int]]: + def _exact_prefix_hashes( + self, + tokens: list[int], + domain_key: tuple[str, ...] | None = None, + ) -> list[tuple[BlockHash, int]]: """Return deterministic hashes for an exact prefix.""" block_hashes_and_token_counts: list[tuple[BlockHash, int]] = [] parent_hash: BlockHash | None = None @@ -1777,12 +1828,11 @@ def _exact_prefix_hashes(self, tokens: list[int]) -> list[tuple[BlockHash, int]] for block_start in range(0, len(tokens), self.block_size): block_tokens = tokens[block_start : block_start + self.block_size] - if split_gdn_layout: - extra_keys = (_EXACT_PREFIX_SPLIT_BLOCK_KEY,) - elif block_start == terminal_start: - extra_keys = (_EXACT_PREFIX_TERMINAL_KEY,) - else: - extra_keys = None + extra_keys = _exact_block_extra_keys( + terminal=block_start == terminal_start, + split_gdn_layout=split_gdn_layout, + domain_key=domain_key, + ) block_hash = compute_block_hash( parent_hash, block_tokens, @@ -1798,13 +1848,14 @@ def fetch_exact_prefix( self, request_id: str, tokens: list[int], + domain_key: tuple[str, ...] | None = None, ) -> BlockTable | None: """Acquire an all-or-nothing exact prefix chain from hot cache or SSD.""" if not tokens or self.paged_ssd_cache is None: return None acquired_blocks: list[CacheBlock] = [] - for block_hash, token_count in self._exact_prefix_hashes(tokens): + for block_hash, token_count in self._exact_prefix_hashes(tokens, domain_key): cached_block = self.paged_cache.cached_block_hash_to_block.get_block( block_hash ) @@ -1851,9 +1902,10 @@ def restore_exact_prefix( tokens: list[int], *, promote_to_hot_cache: bool, + domain_key: tuple[str, ...] | None = None, ) -> list[Any] | None: """Reconstruct a complete exact prefix and release temporary block refs.""" - block_table = self.fetch_exact_prefix(request_id, tokens) + block_table = self.fetch_exact_prefix(request_id, tokens, domain_key) if block_table is None: self._exact_prefix_misses += 1 return None diff --git a/omlx/scheduler.py b/omlx/scheduler.py index 042b5cce3c..dd6bd7a1d7 100644 --- a/omlx/scheduler.py +++ b/omlx/scheduler.py @@ -53,7 +53,7 @@ from .cache.deepseek_v41_delta import compact_snapshot as compact_deepseek_v41_snapshot from .cache.observability import BoundarySnapshotDiagnostics, CacheRateTracker -from .cache.paged_cache import PagedCacheManager +from .cache.paged_cache import BlockTable, PagedCacheManager from .cache.pooling_delta import compact_pooling_cache_snapshot from .cache.prefix_cache import BlockAwarePrefixCache, cachelist_pm_member_plan from .decode_activity import get_decode_activity @@ -12292,23 +12292,50 @@ def _pin_parked_blocks(self, request_id: str, request: Request) -> None: table = manager.get_block_table(request_id) if not table or not table.block_ids: return + self._pin_blocks(request_id, table.block_ids) + + def _pin_exact_chain(self, request_id: str, table: BlockTable) -> bool: + """Hold a stored exact-prefix chain (all blocks or none) for a resume. + + ``store_exact_prefix`` leaves its blocks unreferenced and evictable; + a chain missing any block cannot be restored, so a partial pin would + only hold memory. Released by ``_unpin_parked``. + """ + return self._pin_blocks(request_id, table.block_ids, require_all=True) + + def _pin_blocks( + self, request_id: str, block_ids: list[int], *, require_all: bool = False + ) -> bool: + """Take one block ref per block and pin their hashes in the SSD index. + + Replaces any pins ``request_id`` already holds. A block whose metadata + is gone is skipped, or, with ``require_all``, makes the whole pin fail + and give back the refs it took. Returns whether pins are now held. + """ + manager = self.paged_cache_manager + if manager is None or not block_ids: + return False self._unpin_parked(request_id) - block_ids: list[int] = [] + pinned_ids: list[int] = [] hashes: list[bytes] = [] - for block_id in table.block_ids: + for block_id in block_ids: if not manager.increment_ref(block_id): + if require_all: + manager.release_for_eviction(pinned_ids) + return False continue - block_ids.append(block_id) + pinned_ids.append(block_id) block = manager.allocated_blocks.get(block_id) block_hash = getattr(block, "block_hash", None) if block_hash is not None: hashes.append(bytes(block_hash)) - if not block_ids: - return - self._park_pins[request_id] = _ParkPins(block_ids, hashes) + if not pinned_ids: + return False + self._park_pins[request_id] = _ParkPins(pinned_ids, hashes) ssd = self.paged_ssd_cache_manager if ssd is not None and hasattr(ssd, "pin_blocks"): ssd.pin_blocks(hashes) + return True def _unpin_parked(self, request_id: str) -> None: pins = self._park_pins.pop(request_id, None) diff --git a/tests/test_prefix_cache.py b/tests/test_prefix_cache.py index db00417f0a..bd0a9a6926 100644 --- a/tests/test_prefix_cache.py +++ b/tests/test_prefix_cache.py @@ -563,6 +563,85 @@ def test_exact_prefix_honors_global_hot_cache_only_mode(self, tmp_path): finally: ssd_manager.close() + @staticmethod + def _exact_kv(token_count: int, offset: float) -> list[dict]: + import mlx.core as mx + + keys = mx.arange(token_count, dtype=mx.float32).reshape(1, 1, token_count, 1) + return [ + { + "state": (keys + offset, keys + offset + 0.5), + "meta_state": (token_count,), + "class_name": "KVCache", + "cache_type": "KVCache", + } + ] + + def test_exact_prefix_domains_isolate_identical_token_sequences(self, tmp_path): + """Two requests with the same tokens never read each other's exact chain.""" + import mlx.core as mx + + prefix_cache, _, ssd_manager = self._make_ssd_prefix_cache( + tmp_path / "exact-domains" + ) + tokens = list(range(11)) # two full blocks plus a partial terminal + try: + for domain, offset in ((("req-a",), 0.0), (("req-b",), 100.0)): + stored = prefix_cache.store_exact_prefix( + f"store-{domain[0]}", + tokens, + self._exact_kv(len(tokens), offset), + domain_key=domain, + ) + assert stored is not None and stored.num_tokens == len(tokens) + + for domain, offset in ((("req-a",), 0.0), (("req-b",), 100.0)): + restored = prefix_cache.restore_exact_prefix( + f"restore-{domain[0]}", + tokens, + promote_to_hot_cache=False, + domain_key=domain, + ) + assert restored is not None + keys, _ = restored[0].keys_and_values() + assert keys.shape[2] == len(tokens) + expected = self._exact_kv(len(tokens), offset)[0]["state"][0] + assert mx.array_equal(keys, expected).item() + + # Another domain, or no domain at all, sees nothing. + for domain in (("req-c",), None): + assert ( + prefix_cache.restore_exact_prefix( + "restore-other", + tokens, + promote_to_hot_cache=False, + domain_key=domain, + ) + is None + ) + # Domain blocks never enter ordinary prefix matching. + table, remaining = prefix_cache.fetch_cache("ordinary", [*tokens, 30]) + assert table is None and remaining == [*tokens, 30] + finally: + ssd_manager.close() + + def test_exact_prefix_hashes_depend_on_the_domain(self, tmp_path): + prefix_cache, _, ssd_manager = self._make_ssd_prefix_cache( + tmp_path / "exact-domain-hashes" + ) + tokens = list(range(9)) + try: + plain = prefix_cache._exact_prefix_hashes(tokens) + first = prefix_cache._exact_prefix_hashes(tokens, domain_key=("a",)) + second = prefix_cache._exact_prefix_hashes(tokens, domain_key=("b",)) + assert len(plain) == len(first) == len(second) == 3 + assert not {h for h, _ in plain} & {h for h, _ in first} + assert not {h for h, _ in first} & {h for h, _ in second} + # Deterministic for the same domain. + assert first == prefix_cache._exact_prefix_hashes(tokens, domain_key=("a",)) + finally: + ssd_manager.close() + def test_store_cache_creates_block_table(self, prefix_cache): """Test store_cache creates a block table.""" tokens = [1, 2, 3, 4] # One full block diff --git a/tests/test_scheduler_park.py b/tests/test_scheduler_park.py index 9350dba771..81ceead2cd 100644 --- a/tests/test_scheduler_park.py +++ b/tests/test_scheduler_park.py @@ -559,6 +559,80 @@ def test_pinned_blocks_are_not_evicted_from_the_ssd_index_by_lru( rig.close() +def _stored_exact_chain(rig, request_id, tokens, domain): + """Prefill ``tokens`` for real and store the exact chain under ``domain``.""" + source, state = rig.start(f"{request_id}-source", tokens) + while not rig.step(state, 1): + pass + cache_data, config = rig.scheduler._extract_cache_states(state.cache) + table = rig.prefix.store_exact_prefix( + request_id, + list(tokens[:-1]), + cache_data, + model_cache_config=config, + domain_key=domain, + ) + assert table is not None and table.num_tokens == len(tokens) - 1 + return table + + +def test_an_exact_chain_stays_restorable_while_pinned_and_unpin_releases_it( + tmp_path, mock_tokenizer +): + rig = make_rig(tmp_path, mock_tokenizer) + try: + scheduler = rig.scheduler + tokens = PROMPT_A + table = _stored_exact_chain(rig, "paused", tokens, ("paused",)) + + assert scheduler._pin_exact_chain("paused", table) is True + pins = scheduler._park_pins["paused"] + assert pins.block_ids == table.block_ids + assert len(pins.hashes) == len(table.block_ids) + assert rig.ssd.pinned_block_count == len(pins.hashes) + for block_id in pins.block_ids: + assert rig.paged.allocated_blocks[block_id].ref_count >= 1 + + # An unbounded size enforcement keeps the pinned chain on disk. + rig.ssd._evict_tracked_until_size(0) + restored = rig.prefix.restore_exact_prefix( + "probe", + list(tokens[:-1]), + promote_to_hot_cache=False, + domain_key=("paused",), + ) + assert restored is not None + + scheduler._unpin_parked("paused") + assert "paused" not in scheduler._park_pins + assert rig.ssd.pinned_block_count == 0 + for block_id in pins.block_ids: + block = rig.paged.allocated_blocks.get(block_id) + assert block is None or block.ref_count == 0 + rig.ssd._evict_tracked_until_size(0) + assert all(rig.ssd._index.get(h) is None for h in pins.hashes) + finally: + rig.close() + + +def test_pinning_an_incomplete_exact_chain_takes_no_pins(tmp_path, mock_tokenizer): + """A chain whose block metadata is already gone cannot be held: fail closed.""" + rig = make_rig(tmp_path, mock_tokenizer) + try: + table = _stored_exact_chain(rig, "paused", PROMPT_A, ("paused",)) + rig.paged.allocated_blocks.pop(table.block_ids[-1]) + before = { + b: rig.paged.allocated_blocks[b].ref_count for b in table.block_ids[:-1] + } + assert rig.scheduler._pin_exact_chain("paused", table) is False + assert "paused" not in rig.scheduler._park_pins + assert rig.ssd.pinned_block_count == 0 + for block_id, ref_count in before.items(): + assert rig.paged.allocated_blocks[block_id].ref_count == ref_count + finally: + rig.close() + + # --- Teardown never blocks the MLX thread ------------------------------------------ From efd970ef0ca2d670c9a734071d62c93e30cc7eb4 Mon Sep 17 00:00:00 2001 From: eEvolution author Victor Perez Date: Mon, 5 Oct 2026 14:05:35 -0600 Subject: [PATCH 18/18] fix(memory): wait for a single victim to drain before choosing another 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. --- omlx/engine/batched.py | 6 ++ omlx/engine/vlm.py | 8 ++ omlx/engine_core.py | 32 ++++++- omlx/process_memory_enforcer.py | 118 ++++++++++++++++++++++++-- omlx/request.py | 3 + tests/test_memory_single_victim.py | 50 ++++++++++- tests/test_process_memory_enforcer.py | 118 +++++++++++++++++++++++++- 7 files changed, 319 insertions(+), 16 deletions(-) diff --git a/omlx/engine/batched.py b/omlx/engine/batched.py index 646c89ac62..c6c85fc23b 100644 --- a/omlx/engine/batched.py +++ b/omlx/engine/batched.py @@ -1581,6 +1581,12 @@ async def abort_one_request_for_memory(self, *, spare_parked: bool = True): ) return None + def memory_victim_pending(self, request_id: str) -> bool: + """Whether a memory victim's deferred abort has not run yet.""" + if self._engine and self._engine.engine: + return self._engine.engine.memory_victim_pending(request_id) + return False + async def abort_all_requests( self, *, diff --git a/omlx/engine/vlm.py b/omlx/engine/vlm.py index 9b99f1d57c..891861df80 100644 --- a/omlx/engine/vlm.py +++ b/omlx/engine/vlm.py @@ -6029,6 +6029,14 @@ async def abort_one_request_for_memory(self, *, spare_parked: bool = True): ) return None + def memory_victim_pending(self, request_id: str) -> bool: + """Whether a memory victim's deferred abort has not run yet.""" + if self.is_diffusion_model: + return False + if self._engine and self._engine.engine: + return self._engine.engine.memory_victim_pending(request_id) + return False + async def abort_all_requests( self, *, diff --git a/omlx/engine_core.py b/omlx/engine_core.py index 5304057e08..2819b22a56 100644 --- a/omlx/engine_core.py +++ b/omlx/engine_core.py @@ -21,7 +21,7 @@ import time import uuid from contextlib import suppress -from dataclasses import dataclass, field +from dataclasses import dataclass, field, replace from typing import ( Any, AsyncIterator, @@ -890,7 +890,11 @@ async def abort_one_request_for_memory( The victim is chosen by the scheduler (largest live KV, newest arrival on ties) and receives the same error frame ``abort_all_requests`` sends under memory pressure; every other request keeps running. - Returns the victim, or None when nothing live can be aborted. + Returns the aborted victim, None when nothing live can be chosen, or + the chosen victim with ``skipped`` set ("no_client": no consumer is + attached; "already_finished": its client was already finished) when + it was not aborted. The abort itself runs at the next scheduler step; + ``memory_victim_pending`` tells when it has. """ sched = self.scheduler select = getattr(sched, "select_memory_victim", None) @@ -902,14 +906,29 @@ async def abort_one_request_for_memory( rid = victim.request_id # Only a request with a client attached (and not already finished) is # worth aborting: otherwise the abort frees nothing observable. - if rid not in self._output_collectors or rid in self._finished_at: - return None + if rid not in self._output_collectors: + return replace(victim, skipped="no_client") + if rid in self._finished_at: + return replace(victim, skipped="already_finished") sched.abort_request(rid) self._emit_memory_abort(rid, self._memory_abort_context(None), None, None) self._mark_request_finished(rid) self._wake_engine_loop() return victim + def memory_victim_pending(self, request_id: str) -> bool: + """Whether a memory victim's deferred abort has not run yet. + + True while the scheduler still queues the abort or still holds the + request (and with it the request's KV); False once it is dropped. + """ + sched = self.scheduler + if sched is None: + return False + return request_id in getattr( + sched, "_pending_abort_ids", () + ) or request_id in getattr(sched, "requests", {}) + def _memory_abort_context(self, reason: str | None) -> dict[str, Any]: """Measured usage, limits and advice behind a memory-pressure abort.""" from .utils.proc_memory import get_phys_footprint @@ -1547,6 +1566,11 @@ async def abort_one_request_for_memory( return None return await engine.abort_one_request_for_memory(spare_parked=spare_parked) + def memory_victim_pending(self, request_id: str) -> bool: + """Whether a memory victim's deferred abort has not run yet.""" + engine = getattr(self, "engine", None) + return engine is not None and engine.memory_victim_pending(request_id) + async def abort_all_requests( self, *, diff --git a/omlx/process_memory_enforcer.py b/omlx/process_memory_enforcer.py index f4646146b7..19b0437211 100644 --- a/omlx/process_memory_enforcer.py +++ b/omlx/process_memory_enforcer.py @@ -33,6 +33,7 @@ import subprocess import time from contextlib import suppress +from dataclasses import dataclass from typing import TYPE_CHECKING, Any import mlx.core as mx @@ -379,6 +380,16 @@ def preview_tier_ceilings() -> dict[str, dict[str, Any]]: return previews +@dataclass +class _DrainingVictim: + """The single victim whose memory the enforcer waits on before another.""" + + model_id: str + victim: Any # MemoryVictim + polls: int = 0 # polls since its abort was requested + executed: bool = False # its abort was seen to have run + + class ProcessMemoryEnforcer: """ Background task that enforces process-level memory limits. @@ -475,6 +486,10 @@ def __init__( # Consecutive hard-pressure polls whose abort was deferred in favor of # parking a prefill victim. See _request_scheduler_park. self._park_deferred_polls: int = 0 + # The single victim aborted on the hard path whose memory has not + # settled yet; no other victim is chosen meanwhile. See + # _abort_single_victim. + self._draining_victim: _DrainingVictim | None = None # Last value passed to mx.set_wired_limit (0 if not yet applied # or the call failed). Used by the admin dashboard to surface a # warning when the kernel iogpu.wired_limit_mb is below this. @@ -1282,6 +1297,10 @@ def _shrink_hot_cache_by( # scheduler reports a prefill victim to park (or one just parked). Bounds # the deferral if the scheduler never gets to act on the request. _PARK_DEFER_POLLS_MAX = 30 + # Max polls the next single victim waits for the previous one's abort to + # run and its memory to settle. A prefill chunk can hold the scheduler + # step for ~5 one-second polls, so this covers two chunk boundaries. + _SINGLE_VICTIM_SETTLE_MAX_POLLS = 10 def _pool_bytes(self) -> int: """MLX buffer-pool size, 0 when unreadable (mocked mx in tests).""" @@ -1600,19 +1619,47 @@ def _abort_single_victim_enabled(self) -> bool: async def _abort_single_victim(self, engine: Any, model_id: str) -> Any: """Abort the one request freeing the most memory; None means fall back. - Returns None when the switch is off, the engine has no such hook, or - no live request can be chosen, so the caller aborts everything as - before. At most one victim per call, so the next poll re-measures - before another request is sacrificed. + Returns None when the switch is off, the engine has no such hook, the + hook fails, no live request can be chosen, or the chosen one could + not be aborted (``skipped``), so the caller aborts everything as + before for this poll. The abort itself is deferred to the scheduler + step, so while the previous victim's abort is pending or its memory + has not settled (abort seen to have run, then one more poll) the + same victim is returned and nobody else is sacrificed, for at most + ``_SINGLE_VICTIM_SETTLE_MAX_POLLS`` polls. Emergency pressure never + reaches this path: it aborts everything. """ if not self._abort_single_victim_enabled(): return None abort_one = getattr(engine, "abort_one_request_for_memory", None) if not callable(abort_one): return None - victim = await abort_one(spare_parked=True) + draining = self._still_draining_victim(engine, model_id) + if draining is not None: + return draining + try: + victim = await abort_one(spare_parked=True) + except Exception as exc: # noqa: BLE001 + logger.warning( + "Single-victim abort failed on '%s': %s; falling back to " + "aborting all requests", + model_id, + exc, + ) + return None if victim is None: return None + skipped = getattr(victim, "skipped", None) + if skipped: + logger.warning( + "Single-victim abort skipped %s on '%s' (%s); falling back to " + "aborting all requests", + victim.request_id, + model_id, + skipped, + ) + return None + self._draining_victim = _DrainingVictim(model_id, victim) logger.warning( "Hard memory pressure: aborted 1 victim %s (%d tokens, ~%.1f GB) " "on '%s'; %d request(s) kept", @@ -1624,6 +1671,57 @@ async def _abort_single_victim(self, engine: Any, model_id: str) -> Any: ) return victim + def _still_draining_victim(self, engine: Any, model_id: str) -> Any: + """The previous single victim while its memory settles, else None.""" + draining = self._draining_victim + if draining is None: + return None + draining.polls += 1 + rid = draining.victim.request_id + if draining.model_id != model_id: + self._draining_victim = None + return None + if draining.polls > self._SINGLE_VICTIM_SETTLE_MAX_POLLS: + logger.warning( + "Hard memory pressure: victim %s memory did not drain within %d " + "polls on '%s'; choosing another victim", + rid, + self._SINGLE_VICTIM_SETTLE_MAX_POLLS, + model_id, + ) + self._draining_victim = None + return None + if draining.executed: + # Its abort ran and a further poll was observed: settled. + self._draining_victim = None + return None + draining.executed = not self._victim_abort_pending(engine, rid) + logger.info( + "Hard memory pressure: waiting for victim %s memory to drain on " + "'%s' (poll %d/%d, abort %s)", + rid, + model_id, + draining.polls, + self._SINGLE_VICTIM_SETTLE_MAX_POLLS, + "ran" if draining.executed else "pending", + ) + return draining.victim + + @staticmethod + def _victim_abort_pending(engine: Any, request_id: str) -> bool: + """Whether the engine still holds the victim (abort not run yet). + + An engine without the probe, or a failing probe, counts as run: the + settle poll that follows still lets its memory return. + """ + probe = getattr(engine, "memory_victim_pending", None) + if not callable(probe): + return False + try: + return probe(request_id) is True + except Exception: # noqa: BLE001 + return False + async def _abort_loaded_requests_for_memory_emergency(self) -> int: """Abort active requests on loaded models without unloading them.""" aborted_total = 0 @@ -1825,6 +1923,8 @@ async def _check_and_enforce(self) -> None: self._note_pressure_poll(new_level) if new_level != "hard": self._park_deferred_polls = 0 + # The episode ended: a later one starts without a draining victim. + self._draining_victim = None if new_level == "ok": # The pressure episode ended (drain worked or the load finished): @@ -1995,10 +2095,6 @@ async def _check_and_enforce(self) -> None: and entry.engine is not None and hasattr(entry.engine, "abort_all_requests") ): - # Only the non-emergency path keeps the model - # loaded and lets parked requests resume; an - # emergency unload must abort them, or they keep - # the engine non-idle and the unload never drains. # Deliberate safety brake: only the non-emergency # hard path narrows to one victim. The emergency # path (beyond the ceiling) and model unload keep @@ -2013,6 +2109,10 @@ async def _check_and_enforce(self) -> None: ) if single is not None: break + # Only the non-emergency path keeps the model + # loaded and lets parked requests resume; an + # emergency unload must abort them, or they keep + # the engine non-idle and the unload never drains. aborted = await self._abort_all_requests( entry.engine, spare_parked=not emergency ) diff --git a/omlx/request.py b/omlx/request.py index 62b21ac702..7257919839 100644 --- a/omlx/request.py +++ b/omlx/request.py @@ -103,6 +103,9 @@ class MemoryVictim: tokens: int # live KV tokens (prompt + generated, or prefilled so far) est_bytes: int # estimated KV bytes freed (0 when no estimator is wired) kept: int # live requests left running + # Why the chosen request was NOT aborted ("no_client", "already_finished"), + # None when it was. "No victim at all" is reported as None instead. + skipped: str | None = None @dataclass diff --git a/tests/test_memory_single_victim.py b/tests/test_memory_single_victim.py index baf34c20b3..1c3eb3c7dd 100644 --- a/tests/test_memory_single_victim.py +++ b/tests/test_memory_single_victim.py @@ -206,9 +206,55 @@ async def test_no_victim_aborts_nothing_and_returns_none(self): collectors["a"].put.assert_not_called() @pytest.mark.asyncio - async def test_a_victim_without_a_collector_is_not_reported(self): + async def test_a_victim_without_a_collector_is_reported_as_skipped(self): + """Distinct from "no victim" (None): the caller can tell them apart.""" sched = _scheduler_for_engine("ghost") engine = _engine(sched, {"other": MagicMock()}) - assert await engine.abort_one_request_for_memory() is None + victim = await engine.abort_one_request_for_memory() + + assert victim is not None and victim.request_id == "ghost" + assert victim.skipped == "no_client" sched.abort_request.assert_not_called() + + @pytest.mark.asyncio + async def test_an_already_finished_victim_is_reported_as_skipped(self): + sched = _scheduler_for_engine("done") + collectors = {"done": MagicMock()} + engine = _engine(sched, collectors) + engine._finished_at["done"] = 1.0 + + victim = await engine.abort_one_request_for_memory() + + assert victim is not None and victim.skipped == "already_finished" + sched.abort_request.assert_not_called() + collectors["done"].put.assert_not_called() + + @pytest.mark.asyncio + async def test_an_aborted_victim_is_not_skipped(self): + sched = _scheduler_for_engine("big") + engine = _engine(sched, {"big": MagicMock()}) + + with patch("omlx.utils.proc_memory.get_phys_footprint", return_value=97 * GB): + victim = await engine.abort_one_request_for_memory() + + assert victim.skipped is None + + +class TestMemoryVictimPending: + """The enforcer asks whether a victim's deferred abort has run yet.""" + + def test_pending_until_the_scheduler_has_run_the_abort(self): + sched = SimpleNamespace(_pending_abort_ids={"big"}, requests={"big": 1}) + engine = _engine(sched, {}) + assert engine.memory_victim_pending("big") is True + + sched._pending_abort_ids.clear() # step popped it, abort in progress + assert engine.memory_victim_pending("big") is True + + sched.requests.clear() # _do_abort_request dropped the request + assert engine.memory_victim_pending("big") is False + + def test_no_scheduler_means_nothing_pending(self): + engine = _engine(None, {}) + assert engine.memory_victim_pending("big") is False diff --git a/tests/test_process_memory_enforcer.py b/tests/test_process_memory_enforcer.py index baee873477..2e075dda55 100644 --- a/tests/test_process_memory_enforcer.py +++ b/tests/test_process_memory_enforcer.py @@ -3634,6 +3634,8 @@ def _engine(victims): ] + [None] ) + # Each victim's deferred abort has already run by the next poll. + engine.memory_victim_pending = MagicMock(return_value=False) return engine @staticmethod @@ -3670,7 +3672,7 @@ async def test_hard_pressure_aborts_exactly_one_victim( assert "'big-model'" in caplog.text @pytest.mark.asyncio - async def test_persisting_pressure_aborts_one_more_victim_per_poll( + async def test_persisting_pressure_aborts_the_next_victim_once_the_first_drained( self, enforcer, monkeypatch ): enforcer._single_victim_on = True @@ -3680,10 +3682,124 @@ async def test_persisting_pressure_aborts_one_more_victim_per_poll( await self._tick(enforcer, 97) assert engine.abort_one_request_for_memory.await_count == 1 + # The abort ran; this poll lets its memory return to the OS. await self._tick(enforcer, 97) + assert engine.abort_one_request_for_memory.await_count == 1 + + await self._tick(enforcer, 97) + assert engine.abort_one_request_for_memory.await_count == 2 + engine.abort_all_requests.assert_not_awaited() + + @pytest.mark.asyncio + async def test_no_second_victim_while_the_first_abort_is_pending( + self, enforcer, monkeypatch, caplog + ): + enforcer._single_victim_on = True + engine = self._engine([("first", 2), ("second", 1)]) + engine.memory_victim_pending = MagicMock(side_effect=[True, True, False]) + self._busy(enforcer, engine) + + await self._tick(enforcer, 97) + with caplog.at_level("INFO"): + for _ in range(3): # pending, pending, then ran (settling) + await self._tick(enforcer, 97) + assert engine.abort_one_request_for_memory.await_count == 1 + engine.abort_all_requests.assert_not_awaited() + assert "waiting for victim first memory to drain" in caplog.text + engine.memory_victim_pending.assert_called_with("first") + + await self._tick(enforcer, 97) + assert engine.abort_one_request_for_memory.await_count == 2 + engine.abort_all_requests.assert_not_awaited() + + @pytest.mark.asyncio + async def test_a_victim_that_never_drains_is_waited_on_for_bounded_polls( + self, enforcer, monkeypatch, caplog + ): + enforcer._single_victim_on = True + engine = self._engine([("first", 2), ("second", 1)]) + engine.memory_victim_pending = MagicMock(return_value=True) + self._busy(enforcer, engine) + bound = enforcer._SINGLE_VICTIM_SETTLE_MAX_POLLS + + await self._tick(enforcer, 97) + for _ in range(bound): + await self._tick(enforcer, 97) + assert engine.abort_one_request_for_memory.await_count == 1 + + with caplog.at_level("WARNING"): + await self._tick(enforcer, 97) assert engine.abort_one_request_for_memory.await_count == 2 + assert "did not drain" in caplog.text engine.abort_all_requests.assert_not_awaited() + @pytest.mark.asyncio + async def test_emergency_while_a_victim_drains_aborts_everything( + self, enforcer, monkeypatch + ): + enforcer._single_victim_on = True + engine = self._engine([("first", 2)]) + engine.memory_victim_pending = MagicMock(return_value=True) + self._busy(enforcer, engine) + + await self._tick(enforcer, 97) + await self._tick(enforcer, 103) + + engine.abort_all_requests.assert_awaited_once_with(spare_parked=False) + assert engine.abort_one_request_for_memory.await_count == 1 + + @pytest.mark.asyncio + async def test_relief_below_hard_forgets_the_draining_victim( + self, enforcer, monkeypatch + ): + enforcer._single_victim_on = True + engine = self._engine([("first", 2), ("second", 1)]) + engine.memory_victim_pending = MagicMock(return_value=True) + self._busy(enforcer, engine) + + await self._tick(enforcer, 97) + await self._tick(enforcer, 90) # soft: the episode is over + await self._tick(enforcer, 97) + + assert engine.abort_one_request_for_memory.await_count == 2 + + @pytest.mark.asyncio + async def test_a_failing_hook_falls_back_to_abort_all_for_that_poll( + self, enforcer, monkeypatch, caplog + ): + enforcer._single_victim_on = True + engine = self._engine([]) + engine.abort_one_request_for_memory = AsyncMock( + side_effect=RuntimeError("scheduler gone") + ) + self._busy(enforcer, engine) + + with caplog.at_level("WARNING"): + await self._tick(enforcer, 97) + + engine.abort_all_requests.assert_awaited_once_with(spare_parked=True) + assert "scheduler gone" in caplog.text + assert "falling back to aborting all requests" in caplog.text + + @pytest.mark.asyncio + async def test_a_skipped_victim_falls_back_to_abort_all( + self, enforcer, monkeypatch, caplog + ): + from omlx.request import MemoryVictim + + enforcer._single_victim_on = True + engine = self._engine([]) + engine.abort_one_request_for_memory = AsyncMock( + return_value=MemoryVictim("ghost", 10, 0, 1, skipped="no_client") + ) + self._busy(enforcer, engine) + + with caplog.at_level("WARNING"): + await self._tick(enforcer, 97) + + engine.abort_all_requests.assert_awaited_once_with(spare_parked=True) + assert "ghost" in caplog.text and "no_client" in caplog.text + @pytest.mark.asyncio async def test_recovered_pressure_aborts_no_second_victim( self, enforcer, monkeypatch