fix(pymllm): fix RadixCache evictable size accounting bug
Summary
- Fix
_evictable_sizegoing negative during lock/unlock operations inRadixCache._add_leafsubtracted parent tokens when a leaf gained its first child, but_split_nodedid not make the same adjustment. This broke the invariantevictable + protected == total tree tokens, causing_evictable_sizeto 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
RadixCachecovering 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.
Removed parent-size decrementing logic in RadixCache ๐ฏ 3 (Moderate) | โฑ๏ธ ~20 minutes ๐ I burrowed through leaves and keys so fine, โ๏ธ Tip: You can configure your own custom pre-merge checks in the settings.๐ Walkthrough
Walkthrough
_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.pyRemoved 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.pyAdded 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.pyIn
_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
Poem
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.
โจ Finishing Touches
๐งช Generate unit tests (beta)
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.
Comment @coderabbitai help to get the list of available commands and usage tips.
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)
-
Inconsistency with
_split_nodeโ_split_nodealso 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_sizehas two different semantics depending on how the tree was built. -
Breaks
inc_lock_ref/dec_lock_refโ These methods assume ALL non-root tokens are partitioned intoevictable + protected. When locking walks up the tree and encounters a node whose tokens were already removed by_add_leaf, it subtracts from_evictable_sizeagain, driving it negative (-3, -5 observed in tests). This violates the invariantevictable + protected == total tree tokens. -
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. Soevictable_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_refalready walked up from the locked leaf and subtracted the parent's tokens from_evictable_size. Soevictable_size()won't count them. - There is no scenario where
evictable_size() > 0but 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.