Skip to content

Fix LRUPromptCache: return one-token prefix matches and refresh LRU recency on fetch - #1496

Closed
T0mSIlver wants to merge 1 commit into
ml-explore:mainfrom
T0mSIlver:fix/lru-prompt-cache-search-recency
Closed

T0mSIlver wants to merge 1 commit into
ml-explore:mainfrom
T0mSIlver:fix/lru-prompt-cache-search-recency

Conversation

@T0mSIlver

Copy link
Copy Markdown

Fixes #1495.

Two small fixes in the server's LRUPromptCache, plus a MockCache upgrade so the tests can catch this class of bug:

  1. PromptTrie.search never returned a one-token prefix match. last_index is the index of the deepest node holding a value (-1 = none), so a stored one-token key matches at last_index == 0 and the shorter-prefix check needs >= 0, not > 0. Before this change the entry leaked out as longer=[t] instead, which the longer branch happens to serve for trimmable caches (deepcopy + trim 0) — but for non-trimmable caches the entry was unreachable: the longer branch is skipped and the fetch returned (None, tokens), a full recompute of a cached prefix.

  2. Fetches never refreshed recency, so eviction was FIFO, not LRU. CacheOrder only recorded insertion order and fetch_nearest_cache never touched it, so a hot entry (e.g. a shared system prompt) could be evicted while cold entries survived. fetch_nearest_cache now refreshes the hit entry's position on exact, shorter, and longer hits via a new CacheOrder.touch. The per-type eviction priority is unchanged.

  3. MockCache now has real content semantics: its state is the token list it was computed from, trim() actually slices it and returns the true trimmed count, and __eq__ compares content. The existing test_lru assertions now verify that a fetched cache's contents match the tokens it is served under (previously trim() was a no-op and __eq__ compared an opaque value, so trie navigation was tested but key↔state correspondence was not). Existing tests updated accordingly; two regression tests added (test_lru_one_token_prefix, test_lru_fetch_refreshes_recency).

Both defects and the repros are described in detail in #1495. python -m unittest tests.test_server.TestLRUPromptCache passes (8 tests); black clean.

…ecency on fetch

- PromptTrie.search: a stored one-token key matches at last_index == 0,
  so the shorter-prefix check must be >= 0. Without it, one-token
  prefixes are unreachable for non-trimmable caches (full recompute).
- LRUPromptCache.fetch_nearest_cache now refreshes an entry's recency
  on every hit (exact, shorter, and longer), so eviction is LRU rather
  than insertion order.
- MockCache now models its state as the token list it was computed
  from, with a real trim(), so tests can verify that a fetched cache's
  contents match the tokens it is served under.

Fixes ml-explore#1495
T0mSIlver added a commit to T0mSIlver/localvoxtral that referenced this pull request Jul 7, 2026
Picks up the prompt-cache correctness fixes from the fork:
reuse can no longer serve KV that doesn't match the request prefix
(T0mSIlver/mlx-lm#2, upstream ml-explore/mlx-lm#1494), and the server
cache is actually LRU with one-token prefix hits fixed
(T0mSIlver/mlx-lm#3, upstream PR ml-explore/mlx-lm#1496).

Wheel SHA-256 verified against the published release asset.

@rajanshxrma rajanshxrma left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Following up from #1495 — reviewed the diff and verified this branch independently.

Verification:

  • Full TestLRUPromptCache passes locally (8/8).
  • The new tests are genuine regression coverage: with the cache.py changes reverted and the new tests kept, test_lru_one_token_prefix and test_lru_fetch_refreshes_recency both fail at their documented assertions, and pass again with the fix restored.
  • black --check is clean on both files.

Notes on the changes:

  • last_index >= 0: exact matches are still caught earlier by last_index == len(tokens) - 1 >= 0, and an empty-token query returns before the walk, so widening the shorter branch adds only the previously dropped one-token case. It also has a nice side effect: when a one-token entry and a longer trimmable entry offer the same reusable length (common_prefix == short_length), the fetch now serves the smaller entry directly instead of deep-copying and trimming the longer one.
  • touch() mirrors remove()'s tier scan, so recency refreshes within an entry's own tier and pop()'s per-type eviction priority is preserved. All three hit paths touch the key of the entry actually served — including result.longer on the trim path, which stays the correct stored key since trimming happens on a deepcopy.
  • The MockCache upgrade makes the test_lru assertions verify real key/content correspondence — e.g. the post-trim MockCache([]) and MockCache([1]) expectations weren't expressible with the old opaque-value mock.

LGTM — approving as a non-maintainer; happy to defer to the maintainers on anything further.

GoodOlClint added a commit to GoodOlClint/mlx-swift-lm that referenced this pull request Jul 17, 2026
Swift only reuses a KV cache within a single `ChatSession`. A new request whose
prompt shares a prefix with an earlier one re-processes that prefix from scratch.
Python `mlx_lm` has had a cross-request store for this (`PromptTrie` +
`LRUPromptCache` in `mlx_lm/models/cache.py`, used by `server.py`); this ports it.

Adds:

- `KVCache.nbytes` — byte accounting, the prerequisite for any byte-bounded
  policy. Every Python cache implements `nbytes`; no Swift cache did. The basis
  is the allocated (step-rounded) buffers from `innerState()`, not the
  offset-sliced `state`, matching Python. Declared as an `open var` on
  `BaseKVCache` rather than left to the protocol-extension default, so
  subclasses get a dynamically-dispatched override point.
- `PromptTrie` — prefix trie returning the nearest stored sequence
  (exact / shorter / longer, plus the common-prefix length).
- `LRUPromptCache` — the store: `fetchNearestCache` returning a deep copy and
  the token remainder still to process, prefix trim-reuse, `maxSize`/`maxBytes`
  eviction, type-aware eviction ordering (assistant -> user -> system), and
  `statsByType()`.

The port does not inherit two bugs still open in the Python implementation,
reported in ml-explore/mlx-lm#1495 and fixed there by ml-explore/mlx-lm#1496:
a value stored at a single-token prefix never matched (`search` used `> 0` where
`>= 0` is correct), and eviction ignored fetch recency, making the store FIFO
rather than LRU. Both are pinned by regression tests.

No existing behavior changes: this adds new types plus one protocol requirement
with a default implementation. Nothing is wired into `ChatSession`/`Evaluate`.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@zcbenz

zcbenz commented Aug 21, 2026

Copy link
Copy Markdown
Member

Thanks for the PR but at the moment the number of PRs is way beyond our capacity to review so I'm closing the non-essential ones so we can actually work on this repo.

@zcbenz zcbenz closed this Aug 21, 2026
GoodOlClint added a commit to GoodOlClint/mlx-swift-lm that referenced this pull request Sep 26, 2026
Swift only reuses a KV cache within a single `ChatSession`. A new request whose
prompt shares a prefix with an earlier one re-processes that prefix from scratch.
Python `mlx_lm` has had a cross-request store for this (`PromptTrie` +
`LRUPromptCache` in `mlx_lm/models/cache.py`, used by `server.py`); this ports it.

Adds:

- `KVCache.nbytes`: byte accounting, the prerequisite for any byte-bounded
  policy. The basis is the allocated (step-rounded) buffers from
  `innerState()`, not the offset-sliced `state`, matching Python. Declared as an
  `open var` on `BaseKVCache` rather than left to the protocol-extension
  default, so subclasses get a dynamically-dispatched override point.
- `PromptTrie`: prefix trie returning the nearest stored sequence
  (exact / shorter / longer, plus the common-prefix length).
- `LRUPromptCache`: the store.
  - Caches are copied on insert and on fetch.
  - `LMOutput.State?` is stored with each cache, and a fetch returns the pair
    as a `PromptCacheSnapshot`.
  - An entry carrying state is never trimmed, the rule `PromptCacheReusePolicy`
    applies through `carriesModelState`.
  - A fetch never returns an empty token remainder.
  - `maxSize`/`maxBytes` eviction, ordered by `Chat.Message.Role`
    (tool -> assistant -> user -> system).
  - `statsByType()`.
  - Keys are input token ids; the store is documented as text-only.

The port does not inherit two bugs still open in the Python implementation,
reported in ml-explore/mlx-lm#1495 and fixed there by ml-explore/mlx-lm#1496:
a value stored at a single-token prefix never matched (`search` used `> 0` where
`>= 0` is correct), and eviction ignored fetch recency, making the store FIFO
rather than LRU. Both are pinned by regression tests.

No existing behavior changes: this adds new types plus one protocol requirement
with a default implementation. Nothing is wired into `ChatSession`/`Evaluate`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
GoodOlClint added a commit to GoodOlClint/mlx-swift-lm that referenced this pull request Oct 14, 2026
Swift only reuses a KV cache within a single `ChatSession`. A new request whose
prompt shares a prefix with an earlier one re-processes that prefix from scratch.
Python `mlx_lm` has had a cross-request store for this (`PromptTrie` +
`LRUPromptCache` in `mlx_lm/models/cache.py`, used by `server.py`); this ports it.

Adds:

- `KVCache.nbytes`: byte accounting, the prerequisite for any byte-bounded
  policy. The basis is the allocated (step-rounded) buffers from
  `innerState()`, not the offset-sliced `state`, matching Python. Declared as an
  `open var` on `BaseKVCache` rather than left to the protocol-extension
  default, so subclasses get a dynamically-dispatched override point.
- `PromptTrie`: prefix trie returning the nearest stored sequence
  (exact / shorter / longer, plus the common-prefix length).
- `LRUPromptCache`: the store.
  - Caches are copied on insert and on fetch.
  - `LMOutput.State?` is stored with each cache, and a fetch returns the pair
    as a `PromptCacheSnapshot`.
  - An entry carrying state is never trimmed, the rule `PromptCacheReusePolicy`
    applies through `carriesModelState`.
  - A fetch never returns an empty token remainder.
  - `maxSize`/`maxBytes` eviction, ordered by `Chat.Message.Role`
    (tool -> assistant -> user -> system).
  - `statsByType()`.
  - Keys are input token ids; the store is documented as text-only.

The port does not inherit two bugs still open in the Python implementation,
reported in ml-explore/mlx-lm#1495 and fixed there by ml-explore/mlx-lm#1496:
a value stored at a single-token prefix never matched (`search` used `> 0` where
`>= 0` is correct), and eviction ignored fetch recency, making the store FIFO
rather than LRU. Both are pinned by regression tests.

No existing behavior changes: this adds new types plus one protocol requirement
with a default implementation. Nothing is wired into `ChatSession`/`Evaluate`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

LRUPromptCache: one-token prefixes never match in PromptTrie.search; eviction ignores fetch recency (FIFO, not LRU)

3 participants