From 8ca82118e0e1a0a1b49f85f675843b19ebb388ba Mon Sep 17 00:00:00 2001 From: Liangsheng Yin Date: Thu, 24 Sep 2026 17:23:26 -0700 Subject: [PATCH] [mem_cache] Drop `is_insert` from `cache_finished_req`; release rows from `release_kv_cache` (#40988) --- python/sglang/srt/disaggregation/prefill.py | 8 +- .../sglang/srt/mem_cache/base_prefix_cache.py | 33 ++- python/sglang/srt/mem_cache/chunk_cache.py | 5 +- python/sglang/srt/mem_cache/common.py | 33 +-- .../srt/mem_cache/pure_swa_radix_cache.py | 68 ++---- python/sglang/srt/mem_cache/radix_cache.py | 152 +++++------- .../storage/flexkv/flexkv_radix_cache.py | 11 +- .../storage/lmcache/lmc_radix_cache.py | 16 +- .../unified_cache/components/README.md | 6 +- .../unified_cache/unified_cache_linker.py | 2 +- .../srt/mem_cache/unified_radix_cache.py | 225 +++++++++--------- .../sglang/srt/session/streaming_session.py | 19 +- .../mem_cache/test_decode_radix_lock_ref.py | 40 ++-- .../mem_cache/test_free_kv_row_coalesce.py | 2 +- .../mem_cache/test_pure_swa_chunk_cache.py | 3 +- .../mem_cache/test_pure_swa_radix_cache.py | 2 +- .../unit/mem_cache/test_radix_cache_unit.py | 1 - .../mem_cache/test_streaming_session_unit.py | 5 +- .../test_unified_radix_cache_bench.py | 2 +- .../test_unified_radix_cache_unittest.py | 15 +- .../mem_cache/test_unified_radix_lock_ref.py | 27 ++- 21 files changed, 309 insertions(+), 366 deletions(-) diff --git a/python/sglang/srt/disaggregation/prefill.py b/python/sglang/srt/disaggregation/prefill.py index 88cc5c05b9..7634a932bd 100644 --- a/python/sglang/srt/disaggregation/prefill.py +++ b/python/sglang/srt/disaggregation/prefill.py @@ -1555,12 +1555,10 @@ class SchedulerDisaggregationPrefillMixin: ) self._release_aborted_request(req) # Mamba insertion donates the checkpoint and clears its sequence marker. - release_kv_cache( - req, - self.tree_cache, - is_insert=not uses_write_through_cache - and not self.tree_cache.supports_mamba(), + is_insert = ( + not uses_write_through_cache and not self.tree_cache.supports_mamba() ) + release_kv_cache(req, self.tree_cache, is_insert=is_insert) req.reset_for_retract() req.output_ids = array("q") req.start_send_idx = 0 diff --git a/python/sglang/srt/mem_cache/base_prefix_cache.py b/python/sglang/srt/mem_cache/base_prefix_cache.py index f1992b095a..def8d775b6 100644 --- a/python/sglang/srt/mem_cache/base_prefix_cache.py +++ b/python/sglang/srt/mem_cache/base_prefix_cache.py @@ -418,18 +418,12 @@ class BasePrefixCache(ABC, PrefixCacheTrait): return None @abstractmethod - def cache_finished_req( - self, req: Req, is_insert: bool = True, *, owned_kv_len: int, **kwargs - ): - """Dispose of a finished request's KV. - - ``[0, req.kv.cache_protected_len)`` is cache-owned and must survive. - Every slot in ``[req.kv.cache_protected_len, owned_kv_len)`` is this - call's to account for: insert what can be keyed, release the rest. - Slicing the kv row by the token-id count instead strands whatever - lies between -- no caller releases those. ``release_kv_cache`` frees - everything past ``owned_kv_len``. - """ + def cache_finished_req(self, req: Req, *, owned_kv_len: int, **kwargs): + """Hand a finished request's KV to the tree: insert what can be keyed + (advancing ``cache_protected_len``), ``free_kv_row`` the rest of + ``[cache_protected_len, owned_kv_len)``, ``unpin``. Slicing the row by + token count instead strands the slots up to ``owned_kv_len``; the + caller frees everything past it.""" @abstractmethod def cache_unfinished_req(self, req: Req, **kwargs): @@ -476,6 +470,21 @@ class BasePrefixCache(ABC, PrefixCacheTrait): ) -> DecLockRefResult: pass + def unpin(self, req: Req) -> None: + """Drop the tree lock the request holds on ``req.last_node``; a cache + whose acquire returned a receipt releases with it here.""" + if req.last_node is not None: + self.dec_lock_ref(req.last_node) + + def claim_kv_row(self, req: Req) -> bool: + """A streaming session keeps the request's kv row for the next turn. + Return True after taking the row; the caller then releases nothing.""" + return False + + def on_release(self, req: Req, *, inserted: bool) -> None: + """The row is freed and the lock dropped; ``inserted`` says whether the + KV went into the tree first. Drop per-request state kept outside the tree.""" + def evictable_size(self): return 0 diff --git a/python/sglang/srt/mem_cache/chunk_cache.py b/python/sglang/srt/mem_cache/chunk_cache.py index d608ecdab4..41d59fb0cf 100644 --- a/python/sglang/srt/mem_cache/chunk_cache.py +++ b/python/sglang/srt/mem_cache/chunk_cache.py @@ -76,12 +76,11 @@ class ChunkCache(BasePrefixCache): # ChunkCache does not support prefix caching, so insert is a no-op return InsertResult(prefix_len=0) - def cache_finished_req( - self, req: Req, is_insert: bool = True, *, owned_kv_len: int - ): + def cache_finished_req(self, req: Req, *, owned_kv_len: int): # For decode server: if req.output_ids is empty, we want to free all req.origin_input_ids # The protected prefix is not this req's to free. self.free_kv_row(req.kv, [(req.kv.cache_protected_len, owned_kv_len)]) + self.unpin(req) def cache_unfinished_req(self, req: Req, chunked=False): kv_indices = self.req_to_token_pool.req_to_token[ diff --git a/python/sglang/srt/mem_cache/common.py b/python/sglang/srt/mem_cache/common.py index 0c628fec9d..a34f9d4d7c 100644 --- a/python/sglang/srt/mem_cache/common.py +++ b/python/sglang/srt/mem_cache/common.py @@ -160,7 +160,7 @@ def free_kv_row_segments( def maybe_cache_unfinished_req(req: Req, tree_cache: BasePrefixCache, **kwargs): - if getattr(req, "skip_radix_cache_insert", False): + if req.skip_radix_cache_insert: return tree_cache.cache_unfinished_req(req, **kwargs) @@ -280,6 +280,8 @@ def discard_kv_cache_backup( def release_kv_cache(req: Req, tree_cache: BasePrefixCache, is_insert: bool = True): + """Give the request's kv row back; with ``is_insert`` the tree first keeps + what it can key.""" assert (not req.kv.holds_kv) == req.kv.is_kv_released # A mamba-capable cache may alloc mamba state before alloc KV cache if not req.kv.holds_kv: @@ -293,22 +295,23 @@ def release_kv_cache(req: Req, tree_cache: BasePrefixCache, is_insert: bool = Tr ) req.kv.mamba_pool_idx = None return - - owned_kv_len = req.owned_kv_len() - tree_cache.cache_finished_req( - req, - is_insert=is_insert and not getattr(req, "skip_radix_cache_insert", False), - owned_kv_len=owned_kv_len, - ) - - # StreamingSession.cache_finished_req handles speculative tail trim - # internally, then sets req_pool_idx = None. - assert (not req.kv.holds_kv) == req.kv.is_kv_released - if not req.kv.holds_kv: + if tree_cache.claim_kv_row(req): + # A streaming session detached the kv record to keep the row. + assert not req.kv.holds_kv return - start_p, end_p = owned_kv_len, req.kv.kv_allocated_len - _release_overallocated_kv_indices(req, start_p, end_p, tree_cache) + owned_kv_len = req.owned_kv_len() + is_insert = is_insert and not req.skip_radix_cache_insert + if is_insert: + tree_cache.cache_finished_req(req, owned_kv_len=owned_kv_len) + else: + # The protected prefix is not this req's to free. + tree_cache.free_kv_row(req.kv, [(req.kv.cache_protected_len, owned_kv_len)]) + tree_cache.unpin(req) + _release_overallocated_kv_indices( + req, owned_kv_len, req.kv.kv_allocated_len, tree_cache + ) + tree_cache.on_release(req, inserted=is_insert) # If the prefix cache doesn't manage mamba states, we must free them here. if isinstance(tree_cache.req_to_token_pool, HybridReqToTokenPool) and ( diff --git a/python/sglang/srt/mem_cache/pure_swa_radix_cache.py b/python/sglang/srt/mem_cache/pure_swa_radix_cache.py index 96f600d766..6ad7c227e6 100644 --- a/python/sglang/srt/mem_cache/pure_swa_radix_cache.py +++ b/python/sglang/srt/mem_cache/pure_swa_radix_cache.py @@ -5,15 +5,10 @@ from __future__ import annotations import logging from typing import TYPE_CHECKING -import torch - -from sglang.srt.mem_cache.base_prefix_cache import ( - EvictParams, - EvictResult, - InsertParams, -) +from sglang.srt.mem_cache.base_prefix_cache import EvictParams, EvictResult from sglang.srt.mem_cache.cache_init_params import CacheInitParams -from sglang.srt.mem_cache.radix_cache import RadixCache, RadixKey +from sglang.srt.mem_cache.radix_cache import RadixCache +from sglang.srt.utils.common import ceil_align if TYPE_CHECKING: from sglang.srt.managers.schedule_batch import Req @@ -62,53 +57,22 @@ class PureSWARadixCache(RadixCache): num_tokens = max(params.num_tokens, params.swa_num_tokens) return super().evict(EvictParams(num_tokens=num_tokens)) - def cache_finished_req( - self, req: Req, is_insert: bool = True, *, owned_kv_len: int - ): + def cache_finished_req(self, req: Req, *, owned_kv_len: int): """Insert only the prefill portion [0, evict_floor); free_kv_row skips the span _evict_swa already freed during decode.""" - if self.disable: - self.free_kv_row(req.kv, [(req.kv.cache_protected_len, owned_kv_len)]) - return - - token_ids = (req.origin_input_ids + req.output_ids)[:owned_kv_len] - kv_indices = self.req_to_token_pool.req_to_token[ - req.kv.req_pool_idx, :owned_kv_len - ] - - radix_key = RadixKey( - token_ids, - req.extra_key, - is_bigram=self.is_eagle, - cache_salt=req.cache_salt, - ).page_aligned(self.page_size) - keys_len = len(radix_key) - - old_prefix_len = req.kv.cache_protected_len - swa_evict_floor = req.kv.swa_evict_floor - if self.page_size > 1 and swa_evict_floor > 0: - swa_evict_floor = -(-swa_evict_floor // self.page_size) * self.page_size - if swa_evict_floor > 0: - insert_end = min(swa_evict_floor, keys_len) - else: - insert_end = keys_len - - release_from = old_prefix_len - if is_insert and insert_end > 0: - insert_values = kv_indices[:insert_end].to(dtype=torch.int64, copy=True) - result = self.insert( - InsertParams(key=radix_key[:insert_end], value=insert_values) + if not self.disable: + token_ids = (req.origin_input_ids + req.output_ids)[:owned_kv_len] + swa_evict_floor = req.kv.swa_evict_floor + key_limit = ( + ceil_align(swa_evict_floor, self.page_size) + if swa_evict_floor > 0 + else None ) - self.token_to_kv_pool_allocator.free_segment( - kv_indices[old_prefix_len : result.prefix_len], - start_pos=old_prefix_len, - ) - release_from = insert_end - - self.free_kv_row(req.kv, [(release_from, owned_kv_len)]) - - if req.last_node is not None: - self.dec_lock_ref(req.last_node) + radix_key, _, _ = self._adopt(req, token_ids, key_limit=key_limit) + req.kv.cache_protected_len = len(radix_key) + # The protected prefix is not this req's to free. + self.free_kv_row(req.kv, [(req.kv.cache_protected_len, owned_kv_len)]) + self.unpin(req) def cache_unfinished_req(self, req: Req, chunked=False): """During chunked prefill, swa_evicted_seqlen is 0 and no SWA eviction diff --git a/python/sglang/srt/mem_cache/radix_cache.py b/python/sglang/srt/mem_cache/radix_cache.py index d069b199b3..586e991eeb 100644 --- a/python/sglang/srt/mem_cache/radix_cache.py +++ b/python/sglang/srt/mem_cache/radix_cache.py @@ -433,127 +433,81 @@ class RadixCache(BasePrefixCache): ) return InsertResult(prefix_len=prefix_len, last_device_node=last_node) - def cache_finished_req( - self, req: Req, is_insert: bool = True, *, owned_kv_len: int - ): - """Cache request when it finishes.""" - if self.disable: - # The protected prefix is not this req's to free. - kv_indices = self.req_to_token_pool.req_to_token[ - req.kv.req_pool_idx, req.kv.cache_protected_len : owned_kv_len - ] - self.token_to_kv_pool_allocator.free_segment( - kv_indices, start_pos=req.kv.cache_protected_len - ) - return - - if not is_insert: - # Frees committed slots that no token id names, which the insert - # path below cannot reach; the protected prefix stays with the cache. - kv_indices = self.req_to_token_pool.req_to_token[ - req.kv.req_pool_idx, req.kv.cache_protected_len : owned_kv_len - ] - self.token_to_kv_pool_allocator.free_segment( - kv_indices, start_pos=req.kv.cache_protected_len - ) - if req.last_node is not None: - self.dec_lock_ref(req.last_node) - return - - token_ids = (req.origin_input_ids + req.output_ids)[:owned_kv_len] + def _adopt( + self, + req: Req, + token_ids, + *, + chunked: bool = False, + key_limit: Optional[int] = None, + split_prompt: bool = False, + ) -> Tuple[RadixKey, torch.Tensor, int]: + """Insert the page-aligned key of ``token_ids`` (cut at ``key_limit``) + and free the duplicates it exposed; returns (key, row slice, matched).""" kv_indices = self.req_to_token_pool.req_to_token[ - req.kv.req_pool_idx, :owned_kv_len + req.kv.req_pool_idx, : len(token_ids) ] - radix_key = RadixKey( token_ids, req.extra_key, is_bigram=self.is_eagle, cache_salt=req.cache_salt, ).page_aligned(self.page_size) + if key_limit is not None: + radix_key = radix_key[:key_limit] key_len = len(radix_key) values = kv_indices[:key_len].to(dtype=torch.int64, copy=True) # Radix Cache takes one ref in memory pool - priority = getattr(req, "priority", 0) or 0 + priority = req.priority or 0 result = self.insert( - InsertParams(key=radix_key, value=values, priority=priority) - ) - # A request that was never cached while unfinished can add its - # whole prompt and generated output as one leaf. Split that leaf at - # the prompt boundary so LRU eviction can discard output KV without - # also losing the reusable prompt KV. Reinserting a prefix only - # changes radix topology; it reuses the indices inserted above. - prompt_key = RadixKey( - token_ids[: len(req.origin_input_ids)], - req.extra_key, - is_bigram=self.is_eagle, - cache_salt=req.cache_salt, - ).page_aligned(self.page_size) - if 0 < len(prompt_key) < key_len: - self.insert( - InsertParams( - key=prompt_key, - value=values[: len(prompt_key)], - priority=priority + 1, - # Topology-only re-insert: this request created these - # nodes moments ago, so counting it as a hit is the - # same self-referencing inflation `chunked` exists to - # suppress. hit_count drives eviction order, so an - # extra bump would silently promote every prompt node. - chunked=True, - ) + InsertParams( + key=radix_key, value=values, chunked=chunked, priority=priority ) - freed_end = result.prefix_len - - # duplicates / uninserted range, then the unaligned tail - self.token_to_kv_pool_allocator.free_segments( - [ - ( - kv_indices[req.kv.cache_protected_len : freed_end], - req.kv.cache_protected_len, - ), - (kv_indices[key_len:], key_len), - ] ) + if split_prompt: + # Split the leaf at the prompt boundary so eviction can drop the + # output KV without the prompt; a prefix re-insert only changes topology. + prompt_key = RadixKey( + token_ids[: len(req.origin_input_ids)], + req.extra_key, + is_bigram=self.is_eagle, + cache_salt=req.cache_salt, + ).page_aligned(self.page_size) + if 0 < len(prompt_key) < key_len: + self.insert( + InsertParams( + key=prompt_key, + value=values[: len(prompt_key)], + priority=priority + 1, + # The request created these nodes moments ago; another + # hit_count bump would promote every prompt node. + chunked=True, + ) + ) - # Remove req slot release the cache lock - if req.last_node is not None: - self.dec_lock_ref(req.last_node) + self.token_to_kv_pool_allocator.free_segment( + kv_indices[req.kv.cache_protected_len : result.prefix_len], + start_pos=req.kv.cache_protected_len, + ) + return radix_key, kv_indices, result.prefix_len + + def cache_finished_req(self, req: Req, *, owned_kv_len: int): + """Cache request when it finishes.""" + if not self.disable: + token_ids = (req.origin_input_ids + req.output_ids)[:owned_kv_len] + radix_key, _, _ = self._adopt(req, token_ids, split_prompt=True) + req.kv.cache_protected_len = len(radix_key) + # The protected prefix is not this req's to free. + self.free_kv_row(req.kv, [(req.kv.cache_protected_len, owned_kv_len)]) + self.unpin(req) def cache_unfinished_req(self, req: Req, chunked=False): """Cache request when it is unfinished.""" if self.disable: return - token_ids = req.get_fill_ids() - kv_indices = self.req_to_token_pool.req_to_token[ - req.kv.req_pool_idx, : len(token_ids) - ] - - radix_key = RadixKey( - token_ids, - req.extra_key, - is_bigram=self.is_eagle, - cache_salt=req.cache_salt, - ).page_aligned(self.page_size) - values = kv_indices[: len(radix_key)].to(dtype=torch.int64, copy=True) - - # Radix Cache takes one ref in memory pool - result = self.insert( - InsertParams( - key=radix_key, - value=values, - chunked=chunked, - priority=getattr(req, "priority", 0) or 0, - ) - ) - new_prefix_len = result.prefix_len - - self.token_to_kv_pool_allocator.free_segment( - kv_indices[req.kv.cache_protected_len : new_prefix_len], - start_pos=req.kv.cache_protected_len, - ) + radix_key, kv_indices, _ = self._adopt(req, req.get_fill_ids(), chunked=chunked) # The prefix indices could be updated, reuse it match_result = self.match_prefix(MatchPrefixParams(key=radix_key)) diff --git a/python/sglang/srt/mem_cache/storage/flexkv/flexkv_radix_cache.py b/python/sglang/srt/mem_cache/storage/flexkv/flexkv_radix_cache.py index 0a14cd84ab..fdfd2732d9 100644 --- a/python/sglang/srt/mem_cache/storage/flexkv/flexkv_radix_cache.py +++ b/python/sglang/srt/mem_cache/storage/flexkv/flexkv_radix_cache.py @@ -385,14 +385,15 @@ class FlexKVRadixCache(RadixCache): # cache_finished_req (STORE) # ------------------------------------------------------------------ + def on_release(self, req: Req, *, inserted: bool) -> None: + if not inserted: + self._load_markers.pop(req.cache_request_handle, None) + def cache_finished_req( # type: ignore[override] - self, req: Req, is_insert: bool = True, *, owned_kv_len: int + self, req: Req, *, owned_kv_len: int ) -> None: """Base cache_finished_req then fire an async FlexKV store.""" - super().cache_finished_req(req, is_insert=is_insert, owned_kv_len=owned_kv_len) - if not is_insert: - self._load_markers.pop(req.cache_request_handle, None) - return + super().cache_finished_req(req, owned_kv_len=owned_kv_len) # Compute the committed prefix mirroring LMCRadixCache's logic. topk = get_spec().speculative_eagle_topk diff --git a/python/sglang/srt/mem_cache/storage/lmcache/lmc_radix_cache.py b/python/sglang/srt/mem_cache/storage/lmcache/lmc_radix_cache.py index fdb019bb49..9c2b55c2f5 100644 --- a/python/sglang/srt/mem_cache/storage/lmcache/lmc_radix_cache.py +++ b/python/sglang/srt/mem_cache/storage/lmcache/lmc_radix_cache.py @@ -438,17 +438,15 @@ class LMCRadixCache(RadixCache): ) ) - def cache_finished_req( - self, req: Req, is_insert: bool = True, *, owned_kv_len: int - ) -> None: + def on_release(self, req: Req, *, inserted: bool) -> None: + if not inserted and self._mode is LMCacheMode.MP: + self._mp_load_back_markers.pop(req.rid, None) + self.lmcache_connector.end_session(req.rid) + + def cache_finished_req(self, req: Req, *, owned_kv_len: int) -> None: """On request completion, insert device KV into radix and store to LMCache.""" - super().cache_finished_req(req, is_insert=is_insert, owned_kv_len=owned_kv_len) - if not is_insert: - if self._mode is LMCacheMode.MP: - self._mp_load_back_markers.pop(req.rid, None) - self.lmcache_connector.end_session(req.rid) - return + super().cache_finished_req(req, owned_kv_len=owned_kv_len) topk = get_spec().speculative_eagle_topk enable_kv_committed_len = topk is None or topk == 1 diff --git a/python/sglang/srt/mem_cache/unified_cache/components/README.md b/python/sglang/srt/mem_cache/unified_cache/components/README.md index 491c5f78e6..26f524f9e1 100644 --- a/python/sglang/srt/mem_cache/unified_cache/components/README.md +++ b/python/sglang/srt/mem_cache/unified_cache/components/README.md @@ -228,16 +228,16 @@ receipt proves were taken. The eventual full release must pass --- -### `cache_finished_req(req: Req, is_insert: bool = True, *, owned_kv_len: int)` +### `cache_finished_req(req: Req, *, owned_kv_len: int)` Cache a completed request's KV data into the tree. | Aspect | Detail | |--------|--------| | **Purpose** | After a request finishes, insert its token/KV data into the tree for future reuse | -| **Inputs** | `req` — the finished request; `is_insert` — insert the owned range into the tree (True) or free it (False); `owned_kv_len` — end of the request-owned KV range; slots past it are freed by `release_kv_cache` | +| **Inputs** | `req` — the finished request; `owned_kv_len` — end of the request-owned KV range; slots past it are freed by `release_kv_cache`. A request that leaves without inserting goes through `release_kv_cache(is_insert=False)` instead, which frees the row and calls `on_release(req, inserted=False)` for component cleanup | | **Output** | `None` | -| **Mutation** | Calls component hooks → `insert` → `dec_lock_ref` → component cleanup. Frees unaligned tail KV indices; frees non-inserted KV indices when `is_insert=False`. | +| **Mutation** | Calls component hooks → `insert` → `dec_lock_ref` → component cleanup. Frees unaligned tail KV indices. | | **Complexity** | **O(K + D·C)** — insert O(K + D·C) + lock release O(D). Simplifies to **O(K)**. | **Algorithm detail:** diff --git a/python/sglang/srt/mem_cache/unified_cache/unified_cache_linker.py b/python/sglang/srt/mem_cache/unified_cache/unified_cache_linker.py index 092bb695f5..ff2acee154 100644 --- a/python/sglang/srt/mem_cache/unified_cache/unified_cache_linker.py +++ b/python/sglang/srt/mem_cache/unified_cache/unified_cache_linker.py @@ -363,7 +363,7 @@ class UnifiedCacheLinkerWrapper: req.kv.swa_evicted_seqlen if req.kv is not None else 0 ), chunked=True, - priority=getattr(req, "priority", 0) or 0, + priority=req.priority or 0, track_adopted_ranges=True, ) ) diff --git a/python/sglang/srt/mem_cache/unified_radix_cache.py b/python/sglang/srt/mem_cache/unified_radix_cache.py index b13c268e26..59c75ef0fc 100644 --- a/python/sglang/srt/mem_cache/unified_radix_cache.py +++ b/python/sglang/srt/mem_cache/unified_radix_cache.py @@ -927,6 +927,11 @@ class UnifiedRadixCache(BasePrefixCache): receipt its acquire returned, so it never drops a lock it never took.""" self.dec_lock_ref(req.last_node, req.lock_receipt, skip_swa=skip_swa) + def unpin(self, req: Req) -> None: + # Synthetic profiling requests may own KV without locking a tree node. + if req.last_node is not None: + self._dec_req_lock(req, skip_swa=req.swa_prefix_lock_released) + def dec_swa_lock_only( self, node_id: NodeId, @@ -949,10 +954,7 @@ class UnifiedRadixCache(BasePrefixCache): return DecLockRefResult() return self.tree_core.dec_host_lock_ref(node_id, params) - @rank_consensus(same_params=["req.rid", "is_insert", "owned_kv_len"]) - def cache_finished_req( - self, req: Req, is_insert: bool = True, *, owned_kv_len: int, **kwargs - ) -> None: + def claim_kv_row(self, req: Req) -> bool: # Retraction also enters here: retain its ticket until actual finish. if ( self.cache_controller is not None @@ -960,11 +962,19 @@ class UnifiedRadixCache(BasePrefixCache): and req.finished() ): self.cache_controller.release_pp_prefetch(req.rid) - if self.session.try_cache_finished_req(req, is_insert=is_insert, **kwargs): - return + return self.session.try_cache_finished_req(req) + @rank_consensus(same_params=["req.rid", "inserted"]) + def on_release(self, req: Req, *, inserted: bool) -> None: + if inserted: + return + for comp in self._components_tuple: + comp.cleanup_after_caching_req(req, is_finished=True) + + @rank_consensus(same_params=["req.rid", "owned_kv_len"]) + def cache_finished_req(self, req: Req, *, owned_kv_len: int, **kwargs) -> None: if self.disable: - self.free_kv_row(req.kv, [(0, owned_kv_len)]) + self.free_kv_row(req.kv, [(req.kv.cache_protected_len, owned_kv_len)]) for comp in self._components_tuple: comp.cleanup_after_caching_req(req, is_finished=True) return @@ -974,118 +984,101 @@ class UnifiedRadixCache(BasePrefixCache): req.kv.req_pool_idx, :owned_kv_len ] - result = None - insert_params = None + insert_params = InsertParams( + prev_prefix_len=req.kv.cache_protected_len, + priority=req.priority or 0, + session_id=req.session_id, + rotation_base=req.kv_rotation_base, + ) - if is_insert: - insert_params = InsertParams( - prev_prefix_len=req.kv.cache_protected_len, - priority=getattr(req, "priority", 0) or 0, - session_id=req.session_id, - rotation_base=req.kv_rotation_base, + # components prepare insert data + return effective cache_len + effective_cache_len = len(token_ids) + for comp in self._components_tuple: + cl = comp.prepare_for_caching_req( + req=req, + insert_params=insert_params, + token_ids_len=len(token_ids), + is_finished=True, + ) + if cl is not None: + effective_cache_len = min(effective_cache_len, cl) + for comp in self._components_tuple: + effective_cache_len = comp.floor_cache_len(effective_cache_len) + + # Truncate if needed; the tail free is deferred and batched with + # the unaligned tail below so a shared boundary page is emitted once. + kv_indices_full = kv_indices + tail_free_start = None + if effective_cache_len < len(token_ids): + tail_free_start = max(effective_cache_len, req.kv.cache_protected_len) + token_ids = token_ids[:effective_cache_len] + kv_indices = kv_indices[:effective_cache_len] + + radix_key = RadixKey( + token_ids, + req.extra_key, + is_bigram=self.tree_core.is_eagle, + cache_salt=req.cache_salt, + ).page_aligned(self.page_size) + page_aligned_len = len(radix_key) + values = kv_indices[:page_aligned_len].to(dtype=torch.int64, copy=True) + + insert_params.key = radix_key + insert_params.value = values + result = self.insert(insert_params) + + # Split the leaf at the prompt boundary so eviction can drop the output + # KV without the prompt. prev_prefix_len keeps the overlapping indices + # from being freed as duplicates; skipped after a declined rotation, + # whose rows are freed below. + prompt_key = RadixKey( + req.origin_input_ids, + req.extra_key, + is_bigram=self.tree_core.is_eagle, + cache_salt=req.cache_salt, + ).page_aligned(self.page_size) + if ( + not result.rotation_tail_declined + and len(self._components_tuple) == 1 + and self._components_tuple[0].component_type == BASE_COMPONENT_TYPE + and 0 < len(prompt_key) < len(radix_key) + ): + self.insert( + replace( + insert_params, + key=prompt_key, + value=values[: len(prompt_key)], + prev_prefix_len=len(prompt_key), + priority=insert_params.priority + 1, + # The request created these nodes moments ago; another + # hit_count bump would promote every prompt node. + chunked=True, + ) ) - # components prepare insert data + return effective cache_len - effective_cache_len = len(token_ids) - for comp in self._components_tuple: - cl = comp.prepare_for_caching_req( - req=req, - insert_params=insert_params, - token_ids_len=len(token_ids), - is_finished=True, - ) - if cl is not None: - effective_cache_len = min(effective_cache_len, cl) - for comp in self._components_tuple: - effective_cache_len = comp.floor_cache_len(effective_cache_len) + # Free the unaligned tail and the deferred truncation tail; after a + # rotation decline nothing was inserted, so everything past the + # protected prefix goes. + free_from = ( + # min(): the protected prefix can already run past a truncated + # cache_len, and free_kv_row takes ascending ranges only. + min(req.kv.cache_protected_len, len(kv_indices)) + if result.rotation_tail_declined + else page_aligned_len + ) + ranges = [(free_from, len(kv_indices))] + if tail_free_start is not None: + if free_from < len(kv_indices) and tail_free_start <= len(kv_indices): + # The two halves touch at the truncation boundary and share + # that page; free the union as one range. + ranges[0] = (free_from, len(kv_indices_full)) + else: + ranges.append((tail_free_start, len(kv_indices_full))) + self.free_kv_row(req.kv, ranges) - # Truncate if needed; the tail free is deferred and batched with - # the unaligned tail below so a shared boundary page is emitted once. - kv_indices_full = kv_indices - tail_free_start = None - if effective_cache_len < len(token_ids): - tail_free_start = max(effective_cache_len, req.kv.cache_protected_len) - token_ids = token_ids[:effective_cache_len] - kv_indices = kv_indices[:effective_cache_len] + self.unpin(req) - radix_key = RadixKey( - token_ids, - req.extra_key, - is_bigram=self.tree_core.is_eagle, - cache_salt=req.cache_salt, - ).page_aligned(self.page_size) - page_aligned_len = len(radix_key) - values = kv_indices[:page_aligned_len].to(dtype=torch.int64, copy=True) - - insert_params.key = radix_key - insert_params.value = values - result = self.insert(insert_params) - - # Keep the prompt as an independent radix node. Finished requests - # append a short, request-specific output to a much longer prompt; - # without this split the prompt and output form one leaf and are - # evicted together. Re-inserting the prompt only changes topology: - # prev_prefix_len prevents the overlapping KV indices from being - # treated as duplicate allocations and freed. A declined rotation - # tail releases everything past the protected prefix below, so the - # split is skipped there rather than handing the tree rows that - # are about to be freed. - prompt_key = RadixKey( - req.origin_input_ids, - req.extra_key, - is_bigram=self.tree_core.is_eagle, - cache_salt=req.cache_salt, - ).page_aligned(self.page_size) - if ( - not result.rotation_tail_declined - and len(self._components_tuple) == 1 - and self._components_tuple[0].component_type == BASE_COMPONENT_TYPE - and 0 < len(prompt_key) < len(radix_key) - ): - self.insert( - replace( - insert_params, - key=prompt_key, - value=values[: len(prompt_key)], - prev_prefix_len=len(prompt_key), - priority=insert_params.priority + 1, - # Topology-only re-insert: the request itself created - # these nodes moments ago, so counting it as a hit is - # the same self-referencing inflation `chunked` exists - # to suppress. hit_count drives eviction order, so an - # extra bump here would silently promote every prompt - # node into the protected segment. - chunked=True, - ) - ) - - # Free unaligned tail (+ deferred truncation tail). A rotation - # decline inserted nothing, so the whole span past the protected - # prefix stayed request-owned and is released here instead. - free_from = ( - # min(): the protected prefix can already run past a truncated - # cache_len, and free_kv_row takes ascending ranges only. - min(req.kv.cache_protected_len, len(kv_indices)) - if result.rotation_tail_declined - else page_aligned_len - ) - ranges = [(free_from, len(kv_indices))] - if tail_free_start is not None: - if free_from < len(kv_indices) and tail_free_start <= len(kv_indices): - # The two halves touch at the truncation boundary and share - # that page; free the union as one range. - ranges[0] = (free_from, len(kv_indices_full)) - else: - ranges.append((tail_free_start, len(kv_indices_full))) - self.free_kv_row(req.kv, ranges) - else: - self.free_kv_row(req.kv, [(req.kv.cache_protected_len, owned_kv_len)]) - - # Synthetic profiling requests may own KV without locking a tree node. - if req.last_node is not None: - self._dec_req_lock(req, skip_swa=req.swa_prefix_lock_released) - - if is_insert and result is not None and result.last_device_node is not None: + if result is not None and result.last_device_node is not None: req.last_node = result.last_device_node # cleanup @@ -1112,7 +1105,7 @@ class UnifiedRadixCache(BasePrefixCache): insert_params = InsertParams( prev_prefix_len=req.kv.cache_protected_len, chunked=chunked, - priority=getattr(req, "priority", 0) or 0, + priority=req.priority or 0, rotation_base=req.kv_rotation_base, ) effective_cache_len = len(token_ids) @@ -1164,7 +1157,7 @@ class UnifiedRadixCache(BasePrefixCache): insert_params = InsertParams( prev_prefix_len=req.kv.cache_protected_len, chunked=chunked, - priority=getattr(req, "priority", 0) or 0, + priority=req.priority or 0, session_id=req.session_id, rotation_base=req.kv_rotation_base, ) diff --git a/python/sglang/srt/session/streaming_session.py b/python/sglang/srt/session/streaming_session.py index 82088cd8ad..1ef6fe28dc 100644 --- a/python/sglang/srt/session/streaming_session.py +++ b/python/sglang/srt/session/streaming_session.py @@ -264,9 +264,7 @@ class StreamingSession(BasePrefixCache): cache_protected_len=slot.kv.cache_protected_len, ) - def try_cache_finished_req( - self, req: Req, is_insert: bool = True, **kwargs - ) -> bool: + def try_cache_finished_req(self, req: Req) -> bool: """Handles a streaming-session finish (save slot / mid-abort nuke). Returns True if handled; False means caller runs its raw path.""" if not _is_streaming(req): @@ -354,16 +352,23 @@ class StreamingSession(BasePrefixCache): return result return self.inner.match_prefix(params) - def cache_finished_req(self, req: Req, is_insert: bool = True, **kwargs): - if self.try_cache_finished_req(req, is_insert=is_insert, **kwargs): - return - self.inner.cache_finished_req(req, is_insert=is_insert, **kwargs) + def claim_kv_row(self, req: Req) -> bool: + return self.try_cache_finished_req(req) + + def on_release(self, req: Req, *, inserted: bool) -> None: + self.inner.on_release(req, inserted=inserted) + + def cache_finished_req(self, req: Req, **kwargs): + self.inner.cache_finished_req(req, **kwargs) def cache_unfinished_req(self, req: Req, **kwargs): if self.try_cache_unfinished_req(req, **kwargs): return self.inner.cache_unfinished_req(req, **kwargs) + def unpin(self, req: Req) -> None: + self.inner.unpin(req) + def finish(self, handle: CacheRequestHandle, outcome: CacheRequestOutcome) -> None: self.inner.finish(handle, outcome) diff --git a/test/registered/unit/mem_cache/test_decode_radix_lock_ref.py b/test/registered/unit/mem_cache/test_decode_radix_lock_ref.py index 8f237b6f6b..c606f36aa7 100644 --- a/test/registered/unit/mem_cache/test_decode_radix_lock_ref.py +++ b/test/registered/unit/mem_cache/test_decode_radix_lock_ref.py @@ -11,7 +11,7 @@ transfer scenarios identified in PR #19746: inc_lock_ref(get_new_prebuilt_batch) -> dec+inc(cache_unfinished_req) -> dec(cache_finished_req) 3. Incremental transfer & failure (prefix match > 0, transfer fails) - inc_lock_ref(pop_preallocated) -> dec(cache_finished_req via release_kv_cache is_insert=False) + inc_lock_ref(pop_preallocated) -> dec(unpin via release_kv_cache is_insert=False) 4. Full transfer & failure (prefix match == 0, transfer fails) no inc_lock_ref -> dec(root_node) is no-op since root lock_ref starts at 1 @@ -39,11 +39,13 @@ from sglang.srt.disaggregation.decode_hicache_mixin import ( DecodeHiCacheTransferMixin, DecodePrefixMatch, ) +from sglang.srt.managers.schedule_batch import ReqKvInfo from sglang.srt.mem_cache.base_prefix_cache import ( DecLockRefParams, InsertParams, MatchPrefixParams, ) +from sglang.srt.mem_cache.common import release_kv_cache from sglang.srt.mem_cache.radix_cache import RadixCache, RadixKey from sglang.srt.mem_cache.unified_cache.component_type import ComponentType from sglang.srt.utils.common import Range @@ -57,6 +59,7 @@ def _make_cache_with_pools(page_size=1): """Create a RadixCache with mock pools sufficient for cache_unfinished/finished_req.""" mock_allocator = MagicMock() mock_allocator.device = torch.device("cpu") + mock_allocator.page_size = page_size # req_to_token pool: stores kv indices per request slot max_seq_len = 64 @@ -91,18 +94,20 @@ class MockReq: self.cache_salt = None self.prefix_indices = torch.empty(0, dtype=torch.int64) self.priority = 0 - self.kv = SimpleNamespace( + self.kv = ReqKvInfo( req_pool_idx=req_pool_idx, kv_committed_len=len(fill_ids), kv_allocated_len=len(fill_ids), cache_protected_len=cache_protected_len, - swa_evicted_seqlen=0, ) self.kv_rotation_base = None def get_fill_ids(self): return self.full_untruncated_fill_ids[: self.extend_range.end] + def owned_kv_len(self): + return self.kv.kv_committed_len + def _make_req(fill_ids, req_pool_idx=0, cache_protected_len=0, last_node=None): return MockReq(fill_ids, req_pool_idx, cache_protected_len, last_node) @@ -240,7 +245,7 @@ class TestDecodeLockRefScenarios(CustomTestCase): # Step 2: cache_unfinished_req (dec old lock, inc new lock) cache.cache_unfinished_req(req) - # Step 3: cache_finished_req with is_insert=True (dec lock) + # Step 3: cache_finished_req (dec lock) cache.cache_finished_req(req, owned_kv_len=req.kv.kv_committed_len) # Verify: all non-root nodes should have lock_ref == 0 @@ -304,7 +309,7 @@ class TestDecodeLockRefScenarios(CustomTestCase): must preserve the matched prefix and release the full request-owned suffix. Flow: inc_lock_ref(pop_preallocated) - -> dec_lock_ref(cache_finished_req via release_kv_cache is_insert=False) + -> dec_lock_ref(unpin via release_kv_cache is_insert=False) """ cache, req_to_token = _make_cache_with_pools() @@ -335,17 +340,15 @@ class TestDecodeLockRefScenarios(CustomTestCase): ) req.output_ids = array("q") - # Transfer fails -> cache_finished_req with is_insert=False + # Transfer fails -> discard without inserting cache.token_to_kv_pool_allocator.reset_mock() - cache.cache_finished_req( - req, is_insert=False, owned_kv_len=req.kv.kv_committed_len - ) + release_kv_cache(req, cache, is_insert=False) - free_call = cache.token_to_kv_pool_allocator.free_segment.call_args - torch.testing.assert_close( - free_call.args[0], torch.tensor(full_vals[prefix_len:]) + ((indices, start_pos),) = ( + cache.token_to_kv_pool_allocator.free_segments.call_args.args[0] ) - self.assertEqual(free_call.kwargs["start_pos"], prefix_len) + torch.testing.assert_close(indices, torch.tensor(full_vals[prefix_len:])) + self.assertEqual(start_pos, prefix_len) # The prefix node should be unlocked (back to evictable) self.assertEqual(cache.root_node.lock_ref, 1) @@ -384,9 +387,7 @@ class TestDecodeLockRefScenarios(CustomTestCase): req.kv.kv_allocated_len = len(row_vals) cache.token_to_kv_pool_allocator.reset_mock() - cache.cache_finished_req( - req, is_insert=True, owned_kv_len=req.kv.kv_committed_len - ) + cache.cache_finished_req(req, owned_kv_len=req.kv.kv_committed_len) # The unnamed tail slot is freed as the segment past the radix key. segments = cache.token_to_kv_pool_allocator.free_segments.call_args.args[0] @@ -435,11 +436,8 @@ class TestDecodeLockRefScenarios(CustomTestCase): last_node=matched_node, ) - # Transfer fails -> cache_finished_req with is_insert=False - # dec_lock_ref(root) is a no-op - cache.cache_finished_req( - req, is_insert=False, owned_kv_len=req.kv.kv_committed_len - ) + # Transfer fails -> discard without inserting; dec_lock_ref(root) is a no-op + release_kv_cache(req, cache, is_insert=False) # Root lock unchanged, nothing protected or evictable self.assertEqual(cache.root_node.lock_ref, root_lock_before) diff --git a/test/registered/unit/mem_cache/test_free_kv_row_coalesce.py b/test/registered/unit/mem_cache/test_free_kv_row_coalesce.py index 9f1c4fa153..b08f9d5a47 100644 --- a/test/registered/unit/mem_cache/test_free_kv_row_coalesce.py +++ b/test/registered/unit/mem_cache/test_free_kv_row_coalesce.py @@ -39,7 +39,7 @@ class _RowCache(BasePrefixCache): def match_prefix(self, params): raise NotImplementedError - def cache_finished_req(self, req, is_insert=True, **kwargs): + def cache_finished_req(self, req, **kwargs): raise NotImplementedError def cache_unfinished_req(self, req, **kwargs): diff --git a/test/registered/unit/mem_cache/test_pure_swa_chunk_cache.py b/test/registered/unit/mem_cache/test_pure_swa_chunk_cache.py index 2d1cd97c86..cd81a35872 100644 --- a/test/registered/unit/mem_cache/test_pure_swa_chunk_cache.py +++ b/test/registered/unit/mem_cache/test_pure_swa_chunk_cache.py @@ -36,12 +36,13 @@ class _FakeAllocator: def _make_req(): return SimpleNamespace( + last_node=None, kv=ReqKvInfo( req_pool_idx=0, cache_protected_len=2, swa_evict_floor=3, swa_evicted_seqlen=6, - ) + ), ) diff --git a/test/registered/unit/mem_cache/test_pure_swa_radix_cache.py b/test/registered/unit/mem_cache/test_pure_swa_radix_cache.py index c4fdab8bdb..80368a9a53 100644 --- a/test/registered/unit/mem_cache/test_pure_swa_radix_cache.py +++ b/test/registered/unit/mem_cache/test_pure_swa_radix_cache.py @@ -64,7 +64,7 @@ class TestPureSWARadixCache(CustomTestCase): kv=ReqKvInfo(req_pool_idx=0, swa_evict_floor=4, swa_evicted_seqlen=6), ) - cache.cache_finished_req(req, is_insert=True, owned_kv_len=8) + cache.cache_finished_req(req, owned_kv_len=8) # [0, 4) went into the tree; [4, 6) was window-evicted; [6, 8) is freed. match = cache.match_prefix(MatchPrefixParams(key=RadixKey(token_ids))) diff --git a/test/registered/unit/mem_cache/test_radix_cache_unit.py b/test/registered/unit/mem_cache/test_radix_cache_unit.py index a11faacad0..53002f2f5f 100644 --- a/test/registered/unit/mem_cache/test_radix_cache_unit.py +++ b/test/registered/unit/mem_cache/test_radix_cache_unit.py @@ -494,7 +494,6 @@ class TestRadixCache(CustomTestCase): cache.cache_finished_req( req, - is_insert=True, owned_kv_len=len(prompt_ids) + len(output_ids), ) diff --git a/test/registered/unit/mem_cache/test_streaming_session_unit.py b/test/registered/unit/mem_cache/test_streaming_session_unit.py index 166106dd3e..335117a7ed 100644 --- a/test/registered/unit/mem_cache/test_streaming_session_unit.py +++ b/test/registered/unit/mem_cache/test_streaming_session_unit.py @@ -5,6 +5,7 @@ import torch from sglang.srt.managers.schedule_batch import FINISH_ABORT, ReqKvInfo from sglang.srt.mem_cache.allocator import BaseTokenToKVPoolAllocator from sglang.srt.mem_cache.base_prefix_cache import DecLockRefParams, MatchResult +from sglang.srt.mem_cache.common import release_kv_cache from sglang.srt.session.streaming_session import SessionSlot, StreamingSession from sglang.test.ci.ci_register import register_cpu_ci @@ -194,7 +195,7 @@ def test_first_mid_abort_nukes_ephemeral_slot(): req = _FakeReq("session-a", req_pool_idx=0, committed=0, allocated=20) req.finished_reason = FINISH_ABORT("input too long") - tree_cache.cache_finished_req(req) + release_kv_cache(req, tree_cache) # Slot must NOT be created. assert "session-a" not in tree_cache.slots @@ -222,7 +223,7 @@ def test_nth_mid_abort_nukes_session_slot(): req.finished_reason = FINISH_ABORT("client disconnected") tree_cache.slots["session-a"] = SessionSlot(kv=req.kv, last_node=None) - tree_cache.cache_finished_req(req) + release_kv_cache(req, tree_cache) # Slot wiped — deleted from slots dict. assert "session-a" not in tree_cache.slots diff --git a/test/registered/unit/mem_cache/test_unified_radix_cache_bench.py b/test/registered/unit/mem_cache/test_unified_radix_cache_bench.py index d02c06ee5a..0bf4a5a57d 100644 --- a/test/registered/unit/mem_cache/test_unified_radix_cache_bench.py +++ b/test/registered/unit/mem_cache/test_unified_radix_cache_bench.py @@ -651,7 +651,7 @@ def bench_cache_finished( "cache_finished", lambda: req_items, lambda req: env.tree.cache_finished_req( - req, is_insert=True, owned_kv_len=req.kv.kv_committed_len + req, owned_kv_len=req.kv.kv_committed_len ), len(req_items) - warmup, env.avg_tokens, diff --git a/test/registered/unit/mem_cache/test_unified_radix_cache_unittest.py b/test/registered/unit/mem_cache/test_unified_radix_cache_unittest.py index 517f5305b6..190eb6a344 100644 --- a/test/registered/unit/mem_cache/test_unified_radix_cache_unittest.py +++ b/test/registered/unit/mem_cache/test_unified_radix_cache_unittest.py @@ -43,7 +43,7 @@ from sglang.srt.mem_cache.base_prefix_cache import ( zero_match_result, ) from sglang.srt.mem_cache.cache_init_params import CacheInitParams -from sglang.srt.mem_cache.common import available_and_evictable_str +from sglang.srt.mem_cache.common import available_and_evictable_str, release_kv_cache from sglang.srt.mem_cache.hicache_storage import ( PoolHitPolicy, PoolName, @@ -1755,7 +1755,7 @@ class UnifiedRadixCacheSuite: if self.cfg.has_mamba: req.kv.mamba_last_track_seqlen = kv_len - cache.cache_finished_req(req, is_insert=True, owned_kv_len=req.owned_kv_len()) + cache.cache_finished_req(req, owned_kv_len=req.owned_kv_len()) all_ids = input_ids + output_ids aligned_len = (len(all_ids) // ps) * ps @@ -1816,9 +1816,7 @@ class UnifiedRadixCacheSuite: # cache_finished_req reads get_serving().strip_thinking_cache with get_serving().override(strip_thinking_cache=True): avail_before = allocator.available_size() - cache.cache_finished_req( - req, is_insert=True, owned_kv_len=req.owned_kv_len() - ) + cache.cache_finished_req(req, owned_kv_len=req.owned_kv_len()) start_p, end_p = req.owned_kv_len(), req.kv.kv_allocated_len if ps > 1: start_p = ((start_p + ps - 1) // ps) * ps @@ -1849,6 +1847,7 @@ class UnifiedRadixCacheSuite: kv_indices = self._alloc(allocator, kv_len) req_to_token_pool.write((req.kv.req_pool_idx, slice(0, kv_len)), kv_indices) req.kv.kv_committed_len = kv_len + req.kv.kv_allocated_len = kv_len req.last_node = cache.root_node_handle() req.kv.cache_protected_len = 0 req.lock_receipt = DecLockRefParams() @@ -1860,7 +1859,7 @@ class UnifiedRadixCacheSuite: ) avail_before = allocator.available_size() - cache.cache_finished_req(req, is_insert=False, owned_kv_len=req.owned_kv_len()) + release_kv_cache(req, cache, is_insert=False) self.assertEqual(allocator.available_size(), avail_before + kv_len) m = cache.match_prefix(MatchPrefixParams(key=RadixKey(array("q", tokens)))) @@ -2035,7 +2034,7 @@ class UnifiedRadixCacheSuite: req.kv.mamba_last_track_seqlen = kv_len avail_before = allocator.available_size() - cache.cache_finished_req(req, is_insert=True, owned_kv_len=req.owned_kv_len()) + cache.cache_finished_req(req, owned_kv_len=req.owned_kv_len()) self.assertEqual(allocator.available_size(), avail_before + tail_extra) aligned = input_ids[: (len(input_ids) // ps) * ps] @@ -8738,7 +8737,7 @@ class TestUnifiedRadixCacheInt8MambaCheckpoint(CustomTestCase): ) req.last_node = cache.root_node_handle() - cache.cache_finished_req(req, is_insert=True, owned_kv_len=req.owned_kv_len()) + cache.cache_finished_req(req, owned_kv_len=req.owned_kv_len()) def test_finished_req_stores_radix_mamba_state_in_int8_pool(self): cache, allocator, req_to_token_pool = build_fixture(self.cfg) diff --git a/test/registered/unit/mem_cache/test_unified_radix_lock_ref.py b/test/registered/unit/mem_cache/test_unified_radix_lock_ref.py index 0feb87d6a4..42c87a9bb9 100644 --- a/test/registered/unit/mem_cache/test_unified_radix_lock_ref.py +++ b/test/registered/unit/mem_cache/test_unified_radix_lock_ref.py @@ -3,10 +3,12 @@ import unittest from array import array from types import SimpleNamespace -from unittest.mock import MagicMock +from unittest.mock import MagicMock, patch import torch +from sglang.srt.managers.schedule_batch import ReqKvInfo +from sglang.srt.mem_cache.common import release_kv_cache from sglang.srt.mem_cache.unified_radix_cache import UnifiedRadixCache from sglang.test.ci.ci_register import register_cpu_ci @@ -16,29 +18,48 @@ register_cpu_ci(est_time=7, suite="base-a-test-cpu") class TestUnifiedRadixLockRefScenarios(unittest.TestCase): def test_no_insert_without_last_node_skips_lock_release(self): cache = object.__new__(UnifiedRadixCache) + cache.cache_controller = None cache.session = MagicMock() cache.session.try_cache_finished_req.return_value = False cache.disable = False cache.req_to_token_pool = MagicMock() + cache.token_to_kv_pool_allocator = SimpleNamespace(page_size=1) cache.req_to_token_pool.req_to_token = torch.arange(8).reshape(1, 8) cache.free_kv_row = MagicMock() cache._dec_req_lock = MagicMock() cache._components_tuple = () cache.enable_session_radix_cache = False - kv = SimpleNamespace(req_pool_idx=0, cache_protected_len=0) + kv = ReqKvInfo( + req_pool_idx=0, + kv_committed_len=3, + kv_allocated_len=3, + cache_protected_len=0, + ) req = SimpleNamespace( origin_input_ids=array("q", [1, 2, 3]), output_ids=array("q"), kv=kv, last_node=None, swa_prefix_lock_released=False, + owned_kv_len=lambda: 3, ) - cache.cache_finished_req(req, is_insert=False, owned_kv_len=3) + with ( + patch( + "sglang.srt.mem_cache.common.get_spec", + return_value=SimpleNamespace(speculative_algorithm=None), + ), + patch( + "sglang.srt.mem_cache.common.get_serving", + return_value=SimpleNamespace(strip_thinking_cache=False), + ), + ): + release_kv_cache(req, cache, is_insert=False) cache.free_kv_row.assert_called_once_with(kv, [(0, 3)]) cache._dec_req_lock.assert_not_called() + cache.req_to_token_pool.free.assert_called_once_with(req) if __name__ == "__main__":