mllm icon indicating copy to clipboard operation
mllm copied to clipboard

fix(pymllm): fix RadixCache evictable size accounting bug

Open FarmersWrap opened this issue 8 months ago โ€ข 2 comments

Summary

  • Fix _evictable_size going negative during lock/unlock operations in RadixCache. _add_leaf subtracted parent tokens when a leaf gained its first child, but _split_node did not make the same adjustment. This broke the invariant evictable + protected == total tree tokens, causing _evictable_size to go negative (-3, -5 observed) and potentially leading to incorrect scheduler capacity decisions on memory-constrained devices (e.g. Jetson).
  • Add 51 pytest tests for RadixCache covering insert, match, split, evict, lock/unlock ref counting, namespace isolation, page-aligned ops, SWA mode, pool integration, pool leak detection, and the size invariant. All tests run on CPU in <1s -- no GPU required.

Test plan

  • [x] pytest pymllm/tests/test_radix_cache.py -- 60 tests, all passing
  • [ ] Verify no regression in serving throughput (run pymllm server with radix cache enabled)

Summary by CodeRabbit

  • Bug Fixes

    • Fixed cache memory accounting to avoid incorrect evictable/protected size adjustments during node updates.
    • Added a guard in allocation-with-eviction to stop futile retry loops when eviction frees no resources and return gracefully.
  • Tests

    • Added a comprehensive CPU-only test suite validating radix-cache behavior: inserts, prefix matching, splits, locking, eviction, size invariants, allocator interactions, and SWA scenarios.

FarmersWrap avatar Mar 20 '26 23:03 FarmersWrap

๐Ÿ“ Walkthrough

Walkthrough

Removed parent-size decrementing logic in RadixCache _add_leaf, added a large CPU-only RadixCache test suite, and introduced a guard in the model runner's KV allocation retry loop to abort when eviction reports no progress despite available evictable tokens.

Changes

Cohort / File(s) Summary
Radix cache logic
pymllm/mem_cache/radix_cache.py, pymllm/mem_cache/mamba_radix_cache.py
Removed conditional that decremented evictable/full-evictable counts when converting an internal node from leaf-like to internal in _add_leaf. Parent token accounting is intentionally not adjusted at this point; only the new leaf increments are applied.
New tests (CPU-only)
pymllm/tests/test_radix_cache.py
Added comprehensive end-to-end tests for RadixCache covering insert/match/split semantics, size accounting invariants, lock/ref-count behavior, eviction flows (including SWA), pool allocator interactions, page-alignment, reset semantics, and multiple edge cases and lifecycle scenarios.
Allocator eviction guard
pymllm/orchestrator/model_runner_process.py
In _alloc_kv_with_eviction, after calling cache.evict(evict_target), if full_evicted == 0 while evictable_size > 0, the code now logs a warning and returns None instead of retrying further.

Estimated code review effort

๐ŸŽฏ 3 (Moderate) | โฑ๏ธ ~20 minutes

Poem

๐Ÿ‡ I burrowed through leaves and keys so fine,
Split branches neatly, counted every line.
Tests hopped in sequence, eviction kept pace,
Allocation warned โ€” no more running the race.
A rabbit nods: the cache finds its place.

๐Ÿšฅ Pre-merge checks | โœ… 2 | โŒ 1

โŒ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage โš ๏ธ Warning Docstring coverage is 28.07% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
โœ… Passed checks (2 passed)
Check name Status Explanation
Title check โœ… Passed The title directly and clearly identifies the main issue being fixed: a RadixCache evictable size accounting bug, which is the primary focus across all file changes.
Description check โœ… Passed The PR description includes a comprehensive summary of the bug fix and test additions with clear technical explanations and a test plan, though it references an external guidelines document without full detail.

โœ๏ธ Tip: You can configure your own custom pre-merge checks in the settings.

โœจ Finishing Touches
๐Ÿงช Generate unit tests (beta)
  • [ ] Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

โค๏ธ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar Mar 20 '26 23:03 coderabbitai[bot]

Why the original _add_leaf subtraction was added and why it's incorrect

Context: the original fix (commit 31b0ff91)

The author observed that when a leaf node gains its first child, evictable_size() counts the parent's tokens even though _collect_evictable_leaves() won't find it directly (it has children now). They added a subtraction in _add_leaf to make evictable_size() reflect "directly evictable leaf tokens only":

if (
    len(parent.children) == 0
    and parent != self.root_node
    and parent.lock_ref == 0
    and not parent.evicted
):
    self._evictable_size -= len(parent.key)

Why the subtraction is wrong (3 reasons)

  1. Inconsistency with _split_node โ€” _split_node also creates internal nodes (by splitting a leaf into a parent + child), but does NOT subtract the new parent's tokens from _evictable_size. Same semantic concept (leaf โ†’ internal), different handling. This means _evictable_size has two different semantics depending on how the tree was built.

  2. Breaks inc_lock_ref / dec_lock_ref โ€” These methods assume ALL non-root tokens are partitioned into evictable + protected. When locking walks up the tree and encounters a node whose tokens were already removed by _add_leaf, it subtracts from _evictable_size again, driving it negative (-3, -5 observed in tests). This violates the invariant evictable + protected == total tree tokens.

  3. Internal nodes ARE reclaimable โ€” evict() uses cascade eviction: after evicting all children of a node, the now-childless parent is pushed onto the eviction heap and evicted too. So evictable_size() should include internal node tokens, because they are genuinely reclaimable.

Proof that removing the subtraction is safe

The concern was: could evictable_size() > 0 while evict() can't actually free anything, causing the eviction loop in alloc_kv_with_eviction to spin?

No, because:

  • If an internal node's children are evictable (unlocked) โ†’ cascade eviction works: evict children first, parent becomes childless, cascade evicts parent.
  • If an internal node's children are locked โ†’ inc_lock_ref already walked up from the locked leaf and subtracted the parent's tokens from _evictable_size. So evictable_size() won't count them.
  • There is no scenario where evictable_size() > 0 but nothing is reclaimable.

Safety guard added

As an extra precaution, a guard was added in alloc_kv_with_eviction (model_runner_process.py): if evict() frees 0 tokens despite evictable_size() > 0, the loop breaks with a warning instead of spinning. This covers any theoretical future scenario where the counters could drift.

FarmersWrap avatar Mar 20 '26 23:03 FarmersWrap