Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
8ba5078
feat(scheduler): commit completed prefill blocks to the prefix cache …
e-Evolution Oct 1, 2026
b30e72b
feat(settings): expose prefill_progress_commit_blocks
e-Evolution Oct 1, 2026
bf1611b
fix(settings): reject bool for prefill_progress_commit_blocks
e-Evolution Oct 1, 2026
797f7e4
fix(scheduler): defer prefill commit teardown instead of blocking the…
e-Evolution Oct 1, 2026
1cca37e
fix(scheduler): drain deferred teardowns on reap, skip held ids, canc…
e-Evolution Oct 1, 2026
2be1339
fix(scheduler): bound the final store's wait on an in-flight prefill …
e-Evolution Oct 1, 2026
beea871
refactor(scheduler): move the prefill commit executor into its own mo…
e-Evolution Oct 2, 2026
e37bdfc
feat(enforcer): request a prefill park before aborting at hard pressure
e-Evolution Oct 1, 2026
21dc190
feat(scheduler): park a chunked prefill under memory pressure instead…
e-Evolution Oct 1, 2026
3c459e2
fix(engine): spare parked requests only when the caller keeps the mod…
e-Evolution Oct 1, 2026
4fed9d3
fix(scheduler): bound the park hold gate and let a parked head pass w…
e-Evolution Oct 1, 2026
5ed4e22
fix(scheduler): resume parked requests one per window and keep parked…
e-Evolution Oct 1, 2026
96c8c5c
refactor(scheduler): name the resume-poll saturation sentinel and tes…
e-Evolution Oct 2, 2026
289a9d4
fix(scheduler): commit prefill progress for media prompts and log eve…
e-Evolution Oct 2, 2026
7be0291
fix(scheduler): keep shutdown waits on prefill commits inside the tea…
e-Evolution Oct 2, 2026
4ddc6a4
feat(memory): abort one victim instead of all when nothing is parkable
e-Evolution Oct 5, 2026
4b30e60
feat(cache): domain-isolated exact-prefix chains and exact-chain pins
e-Evolution Oct 5, 2026
efd970e
fix(memory): wait for a single victim to drain before choosing another
e-Evolution Oct 5, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions docs/TESTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,3 +228,17 @@ 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.

# 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.

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.
54 changes: 51 additions & 3 deletions omlx/cache/paged_ssd_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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]))
Expand Down
100 changes: 80 additions & 20 deletions omlx/cache/prefix_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -899,6 +923,8 @@ 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,
_exact_domain_key: tuple[str, ...] | None = None,
) -> BlockTable | None:
"""
Store computed cache for future reuse.
Expand Down Expand Up @@ -926,6 +952,13 @@ 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.
_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
Expand Down Expand Up @@ -1188,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,
Expand All @@ -1211,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,
Expand Down Expand Up @@ -1333,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(
Expand All @@ -1356,8 +1400,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
Expand Down Expand Up @@ -1689,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.

Expand All @@ -1697,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
Expand Down Expand Up @@ -1741,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)
Expand All @@ -1757,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
Expand All @@ -1769,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,
Expand All @@ -1790,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
)
Expand Down Expand Up @@ -1843,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
Expand Down
16 changes: 16 additions & 0 deletions omlx/engine/batched.py
Original file line number Diff line number Diff line change
Expand Up @@ -1573,16 +1573,32 @@ 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

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,
*,
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
Loading
Loading