diff --git a/python/sglang/srt/mem_cache/buffer_mode/pipeline.py b/python/sglang/srt/mem_cache/buffer_mode/pipeline.py index fc672c8672..71f1de33c0 100644 --- a/python/sglang/srt/mem_cache/buffer_mode/pipeline.py +++ b/python/sglang/srt/mem_cache/buffer_mode/pipeline.py @@ -897,10 +897,11 @@ class BufferModePipeline: if not (req.host_hit_is_storage and req.host_loaded_length > 0): self._clear_storage_hit(req) return True - if len(req.prefix_indices) >= f.matched_len + f.num_tokens: + joint_len = len(req.prefix_indices) + if joint_len >= f.matched_len + f.num_tokens: # The joint match already covers the staged span; a shorter FULL-only # prefix would strand the slots recomputed below cache_protected_len. - self._resolve_device_covered(req, f) + self._resolve_device_covered(req) return True key = RadixKey( f.key_tokens, @@ -935,26 +936,25 @@ class BufferModePipeline: if t.name == PoolName.SWA and t.host_indices is not None ) if full_tokens == 0 and swa_tokens == 0: - self._resolve_device_covered(req, f) + self._resolve_device_covered(req) return True req.host_hit_length = full_tokens req.swa_host_hit_length = swa_tokens - req.storage_hit_length = full_tokens - req.storage_hit_start = matched_len if full_tokens else None + # The device alone serves only this pass's joint match; the rest of the + # span, fetched FULL or resident FULL the aux tail unlocks, is storage's. + req.storage_hit_length = f.matched_len + f.num_tokens - joint_len + req.storage_hit_start = joint_len req.host_hit_is_storage = True req.staged_prefetch_plan = StagedPrefetchPlan( f.operation_id, key, matched_len, full_tokens, swa_tokens ) return True - def _resolve_device_covered(self, req: Req, f: _StagedPrefetch) -> None: + def _resolve_device_covered(self, req: Req) -> None: req.host_hit_length = 0 req.swa_host_hit_length = 0 self._clear_storage_hit(req) - self._cache._resolve_storage_prefetch_tokens( - req.cache_request_handle, f.num_tokens, reason="device_covered" - ) - self.release_staged_hold(req.cache_request_handle, reason=None) + self.release_staged_hold(req.cache_request_handle, reason="device_covered") @staticmethod def _clear_storage_hit(req: Req) -> None: @@ -1162,8 +1162,8 @@ class BufferModePipeline: del self.staged_prefetches[request] self._staged_admission_defers.pop(request, None) req.staged_prefetch_plan = None - cache._resolve_storage_prefetch_tokens( - request, trim_tokens, reason="device_covered" + cache._settle_storage_prefetch_hit( + request, credited_tokens=req.storage_hit_length ) swa_dev = next( diff --git a/python/sglang/srt/mem_cache/unified_radix_cache.py b/python/sglang/srt/mem_cache/unified_radix_cache.py index 421a215722..bf81330713 100644 --- a/python/sglang/srt/mem_cache/unified_radix_cache.py +++ b/python/sglang/srt/mem_cache/unified_radix_cache.py @@ -2559,6 +2559,17 @@ class UnifiedRadixCache(BasePrefixCache): unfulfilled, reason ) + def _settle_storage_prefetch_hit( + self, request: CacheRequestHandle, credited_tokens: int + ) -> None: + """At buffer-mode admission, hit tokens not credited to storage were + covered by the device's joint match; the rest resolve at the fill ack.""" + remaining = self._storage_prefetch_hit_remaining_by_reqid.get(request) + if remaining is not None: + self._resolve_storage_prefetch_tokens( + request, remaining - credited_tokens, reason="device_covered" + ) + def finish_storage_prefetch_admission( self, request: CacheRequestHandle, fulfilled_tokens: int, reason: Optional[str] ) -> None: @@ -2775,9 +2786,8 @@ class UnifiedRadixCache(BasePrefixCache): ) self.ongoing_prefetch[request] = info self.cache_controller.trim_prefetch_full_head(operation, trim_tokens) - self._resolve_storage_prefetch_tokens( - request, trim_tokens, reason="device_covered" - ) + # Labeled at admission: FULL reusable only with the fetched aux tail is a + # storage hit there, not device_covered. return info, hit_tokens - trim_tokens, original_hit_tokens def revoke_pending_prefetch(self, request: CacheRequestHandle) -> None: diff --git a/test/registered/unit/mem_cache/test_storage_prefetch_lifecycle.py b/test/registered/unit/mem_cache/test_storage_prefetch_lifecycle.py index 29331c03f5..a3a3b7728a 100644 --- a/test/registered/unit/mem_cache/test_storage_prefetch_lifecycle.py +++ b/test/registered/unit/mem_cache/test_storage_prefetch_lifecycle.py @@ -11,6 +11,7 @@ from unittest.mock import Mock import torch +from sglang.srt.managers.schedule_batch import split_cached_prefix_by_tier from sglang.srt.mem_cache.base_prefix_cache import ( CacheRequestHandle, InitLoadBackParams, @@ -302,6 +303,60 @@ class TestStagedPrefetchLifecycle(unittest.TestCase): self.assertFalse(pipeline.has_staged(req.cache_request_handle)) cache.tree_core.match_full_device_prefix.assert_not_called() + def test_storage_credit_starts_at_the_joint_device_match(self): + """At admission, storage is credited with everything past the device's + joint FULL+aux match, resident FULL the fetched aux tail unlocks + included; only hit tokens that match covers are device_covered.""" + cache, pipeline, req = _staged_fixture() + pipeline.staged_prefetches.clear() + handle = req.cache_request_handle + tokens = array("q", range(10)) + cache.prefetch_from_storage( + handle, + 0, + tokens[2:], + matched_prefix_tokens=tokens[:2], + storage_hit_end=10, + ) + info = cache.ongoing_prefetch[handle] + operation = info.operation + operation.hash_value = ["h0", "h1", "h2", "h3"] + operation.storage_hit_count = 8 + collector = cache.storage_metrics_collector = Mock() + cache._storage_prefetch_hit_remaining_by_reqid[handle] = 8 + # FULL [2, 8) is on device: only [8, 10) and the SWA tail are fetched. + info, hit_tokens, _ = cache._trim_buffer_prefetch_full_head( + handle, info, operation, 8, 8 + ) + swa = PoolTransfer(name=PoolName.SWA, host_indices=torch.arange(4)) + operation.pool_transfers = [swa] + operation.host_indices = torch.arange(hit_tokens) + cache.ongoing_prefetch[handle] = info._replace( + host_indices=operation.host_indices, comp_xfers={"swa": [swa]} + ) + cache.storage_existence_cache = Mock() + pipeline.stage_completed_prefetch(handle, hit_tokens, operation.hash_value) + + # A twin made [0, 6) jointly reusable while the fetch was held. + cache.tree_core.match_full_device_prefix.return_value = (8, 1, 8) + req.prefix_indices = torch.arange(6) + self.assertTrue(pipeline.prepare_staged_prefetch(req)) + self.assertEqual( + split_cached_prefix_by_tier( + prefix_len=10, + host_hit_len=req.host_hit_length, + storage_hit_len=req.storage_hit_length, + storage_hit_start=req.storage_hit_start, + host_hit_is_storage=req.host_hit_is_storage, + ), + (6, 0, 4), + ) + collector.log_storage_prefetch_unfulfilled_tokens.assert_not_called() + cache._settle_storage_prefetch_hit(handle, credited_tokens=4) + collector.log_storage_prefetch_unfulfilled_tokens.assert_called_once_with( + 4, "device_covered" + ) + def test_two_rank_completion_capacity_and_anchor_loss(self): with tempfile.TemporaryDirectory(prefix="prefetch-rank-test-") as directory: torch.multiprocessing.spawn( 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 a046833edb..1d78b8a068 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 @@ -4770,9 +4770,9 @@ class UnifiedRadixCacheSuite: after = cons.match_prefix(MatchPrefixParams(key=RadixKey(array("q", seq)))) self.assertEqual(after.full_kv_hit_length, len(seq)) self.assertEqual(len(after.device_indices), len(seq)) - cons.storage_metrics_collector.log_storage_prefetch_unfulfilled_tokens.assert_called_once_with( - len(seq), "device_covered" - ) + # Only the fetched SWA tail made the resident FULL reusable. + self.assertEqual((req.storage_hit_start, req.storage_hit_length), (0, len(seq))) + cons.storage_metrics_collector.log_storage_prefetch_unfulfilled_tokens.assert_not_called() cons.sanity_check() def test_buffer_only_load_back_reuses_partial_masked_full(self):