Skip to content

vllm.distributed.kv_transfer.kv_connector.v1.mooncake.store.worker

Worker-side logic for MooncakeStoreConnector.

Includes the store worker, transfer threads, lookup server, and MooncakeDistributedStore integration.

Classes:

Functions:

KVCacheStoreRecvingThread

Bases: KVTransferThread

Background thread for loading KV cache blocks from the store.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
class KVCacheStoreRecvingThread(KVTransferThread):
    """Background thread for loading KV cache blocks from the store."""

    def __init__(
        self,
        store: Any,
        coord: MooncakeStoreCoordinator,
        token_databases: list[ChunkedTokenDatabase],
        block_size: int,
        tp_rank: int,
        ready_event: threading.Event,
        disk_offload_buffer_budget_bytes: int | None = None,
        record_operation: Callable[..., None] | None = None,
        request_queue: queue.Queue[Any] | None = None,
    ):
        super().__init__(
            store,
            token_databases,
            block_size,
            tp_rank,
            ready_event,
            name="KVCacheStoreRecvingThread",
            record_operation=record_operation,
            request_queue=request_queue,
        )
        # _invalid_block_ids can be access by both the Worker and RecvingThread
        self._invalid_block_ids_lock = threading.Lock()
        self._invalid_block_ids: set[int] = set()
        self.disk_offload_buffer_budget_bytes = disk_offload_buffer_budget_bytes
        self.usable_disk_offload_buffer_budget_bytes = (
            None
            if disk_offload_buffer_budget_bytes is None
            else _get_usable_disk_offload_buffer_budget_bytes(
                disk_offload_buffer_budget_bytes
            )
        )
        self.coord = coord

    def _add_load_error_block_ids(self, block_ids: list[int]) -> None:
        with self._invalid_block_ids_lock:
            self._invalid_block_ids.update(block_ids)

    def get_and_clear_block_ids_with_load_errors(self) -> set[int]:
        with self._invalid_block_ids_lock:
            invalid_block_ids = self._invalid_block_ids.copy()
            self._invalid_block_ids.clear()
        return invalid_block_ids

    def _handle_request(self, req_meta: ReqMeta):
        token_len = req_meta.load_spec.token_len  # type: ignore[union-attr]
        req_id = req_meta.req_id
        mask_num = (
            req_meta.load_spec.vllm_cached_tokens  # type: ignore[union-attr]
            // self.block_size
            * self.block_size
        )

        # Skip chunks the consumer's per-group spec wouldn't populate
        # locally (e.g. SWA pre-window) even if the producer stored them.
        load_mask_per_group = self.coord.load_mask(req_meta.block_hashes, token_len)

        addr_list: list[list[int]] = []
        size_list: list[list[int]] = []
        key_list: list[str] = []
        block_id_list: list[int] = []
        for g_idx, db in enumerate(self.token_databases):
            mask = load_mask_per_group[g_idx]
            chunks: list[tuple[int, int]] = []
            for start, end, block_hash in db.process_tokens(
                token_len, req_meta.block_hashes, mask_num
            ):
                chunk_idx = start // db.block_size
                if chunk_idx >= len(mask) or not mask[chunk_idx]:
                    continue
                key_list.append(db.key_for(block_hash))
                chunks.append((start, end))
            g_addrs, g_sizes, g_block_ids = db.prepare_values(
                chunks, req_meta.block_ids[g_idx]
            )
            addr_list.extend(g_addrs)
            size_list.extend(g_sizes)
            block_id_list.extend(g_block_ids)

        # Rotate aligned lists by tp_rank for load balancing.
        rotation = self.tp_rank % len(key_list)
        key_list_c = _rotate_list(key_list, rotation)
        addr_list_c = _rotate_list(addr_list, rotation)
        size_list_c = _rotate_list(size_list, rotation)
        block_id_list_c = _rotate_list(block_id_list, rotation)

        load_batches = [(key_list_c, addr_list_c, size_list_c, block_id_list_c)]
        if self.usable_disk_offload_buffer_budget_bytes is not None:
            total_staging_bytes = sum(
                _estimate_disk_offload_staging_bytes(size) for size in size_list_c
            )
            if total_staging_bytes > self.usable_disk_offload_buffer_budget_bytes:
                assert self.disk_offload_buffer_budget_bytes is not None
                split_batches, oversized_key = _split_disk_offload_load_batches(
                    key_list_c,
                    addr_list_c,
                    size_list_c,
                    self.usable_disk_offload_buffer_budget_bytes,
                    self.disk_offload_buffer_budget_bytes,
                )
                if oversized_key is not None:
                    oversized_key_index = key_list_c.index(oversized_key)
                    # Mark every block: we skip the whole request, and the
                    # tp_rank rotation means oversized_key isn't necessarily
                    # the first block in the request's original order.
                    self._add_load_error_block_ids(block_id_list_c)
                    oversized_key_bytes = _estimate_disk_offload_staging_bytes(
                        size_list_c[oversized_key_index]
                    )
                    logger.warning(
                        "Skipping Mooncake load for request %s because key %s "
                        "requires %d staging bytes, exceeding budget %d",
                        req_id,
                        oversized_key,
                        oversized_key_bytes,
                        self.disk_offload_buffer_budget_bytes,
                    )
                    self.set_finished_request(req_id)
                    self.request_queue.task_done()
                    return
                load_batches = []
                block_id_offset = 0
                for batch_keys, batch_addrs, batch_sizes in split_batches:
                    next_block_id_offset = block_id_offset + len(batch_keys)
                    batch_block_ids = block_id_list_c[
                        block_id_offset:next_block_id_offset
                    ]
                    load_batches.append(
                        (batch_keys, batch_addrs, batch_sizes, batch_block_ids)
                    )
                    block_id_offset = next_block_id_offset

        current_batch_keys: list[str] = key_list_c
        current_batch_block_ids: list[int] = block_id_list_c
        batch_bytes = 0
        try:
            for batch_keys, batch_addrs, batch_sizes, batch_block_ids in load_batches:
                current_batch_keys = batch_keys
                current_batch_block_ids = batch_block_ids
                batch_bytes = _sum_batch_bytes(batch_sizes)
                tiers_by_key: dict[str, str] | None = None
                if envs.VLLM_MOONCAKE_STORE_TIER_LOG:
                    tiers_by_key = _get_replica_tiers_by_key(self.store, batch_keys)
                # Reset so the recorded RPC duration excludes tier lookup.
                load_get_start = time.perf_counter()
                res = self.store.batch_get_into_multi_buffers(
                    batch_keys, batch_addrs, batch_sizes
                )
                if tiers_by_key is not None:
                    _log_mooncake_load_tier_summary(
                        req_id, batch_keys, res, tiers_by_key
                    )
                failed = [
                    (key, value, block_id)
                    for key, value, block_id in zip(
                        batch_keys, res, batch_block_ids, strict=True
                    )
                    if value < 0
                ]
                self._record_operation(
                    "load_get",
                    load_get_start,
                    len(batch_keys),
                    num_bytes=batch_bytes,
                    status="partial_failure" if failed else "ok",
                    num_failed_keys=len(failed),
                )
                if failed:
                    self._add_load_error_block_ids(
                        [block_id for _, _, block_id in failed]
                    )
                    logger.warning(
                        "Failed to get %d Mooncake keys from sub-batch "
                        "(batch_keys=%d, first_failures=%s)",
                        len(failed),
                        len(batch_keys),
                        [(key, value) for key, value, _ in failed[:3]],
                    )
                    break
        except Exception as e:
            self._add_load_error_block_ids(current_batch_block_ids)
            self._record_operation(
                "load_get",
                load_get_start,
                len(current_batch_keys),
                num_bytes=batch_bytes,
                status="error",
                num_failed_keys=len(current_batch_keys),
            )
            logger.warning(
                "Failed to get Mooncake sub-batch %s, error: %s",
                current_batch_keys[:3],
                e,
            )

        self.set_finished_request(req_id)
        self.request_queue.task_done()

KVCacheStoreSendingThread

Bases: KVTransferThread

Background thread for storing KV cache blocks to the store.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
class KVCacheStoreSendingThread(KVTransferThread):
    """Background thread for storing KV cache blocks to the store."""

    def __init__(
        self,
        store: Any,
        coord: MooncakeStoreCoordinator,
        token_databases: list[ChunkedTokenDatabase],
        block_size: int,
        tp_rank: int,
        group_put_steps: Sequence[int],
        kv_role: str,
        ready_event: threading.Event,
        enable_kv_event: bool = False,
        replicate_config: Any = None,
        enable_group_semantics: bool = False,
        supports_group_ids: bool = False,
        record_operation: Callable[..., None] | None = None,
    ):
        super().__init__(
            store,
            token_databases,
            block_size,
            tp_rank,
            ready_event,
            name="KVCacheStoreSendingThread",
            record_operation=record_operation,
        )
        # Only ranks with identical group bytes may stripe PUTs (e.g., MLA).
        self.group_put_steps = group_put_steps
        self.coord = coord
        self.kv_role = kv_role
        self.stored_requests: defaultdict[str, int] = defaultdict(int)
        self.enable_kv_event = enable_kv_event
        # Caller always passes a non-None ReplicateConfig — see
        # MooncakeStoreWorker.__init__ where store_replicate_config is built.
        self.replicate_config = replicate_config
        self.enable_group_semantics = enable_group_semantics
        self.supports_group_ids = supports_group_ids

        # Pause store requests when CPU/disk offloading is under pressure.
        self._store_pressure_active = False
        self._skip_store_requests: set[str] = set()

        # Per-request high-water mark of tokens actually persisted; the next
        # batch resumes here, so pressure-skipped or failed ranges are retried.
        self._saved_offset: dict[str, int] = {}

    def add_stored_request(self, req_id: str):
        with self.done_task_lock:
            self.stored_requests[req_id] += 1

    def dec_stored_request(self, req_id: str):
        with self.done_task_lock:
            if req_id in self.stored_requests:
                self.stored_requests[req_id] -= 1

    def delete_finished_stored_request(self, req_id: str):
        with self.done_task_lock:
            if req_id in self.stored_requests:
                del self.stored_requests[req_id]
            self._skip_store_requests.discard(req_id)
            self._saved_offset.pop(req_id, None)

    def _record_saved(self, req_id: str, token_len: int) -> None:
        # Guard on liveness so a concurrent finish/preempt pop isn't recreated.
        with self.done_task_lock:
            if req_id in self.stored_requests:
                self._saved_offset[req_id] = token_len

    def _should_skip_request(self, req_id: str) -> bool:
        with self.done_task_lock:
            return self._store_pressure_active and req_id in self._skip_store_requests

    def _mark_request_skipped_for_pressure(self, req_id: str) -> bool:
        with self.done_task_lock:
            already_skipped = req_id in self._skip_store_requests
            self._store_pressure_active = True
            self._skip_store_requests.add(req_id)
        return already_skipped

    def _clear_store_pressure(self) -> bool:
        with self.done_task_lock:
            if not self._store_pressure_active and not self._skip_store_requests:
                return False
            self._store_pressure_active = False
            self._skip_store_requests.clear()
        return True

    def _maybe_offload_partial_tail(self, req_meta: ReqMeta) -> bool:
        """Offload the request's sub-block partial tail (its last prompt hash
        boundary) so a later request can hit the sub-block prefix.

        Covers every block from the normal save's lcm floor to the boundary:
        the normal save floors to ``lcm_block_size``, so a smaller-block
        group's full blocks in that gap are never persisted elsewhere, and
        the consumer's lookup needs every group at every probed boundary.
        Full blocks are keyed by their block-end hash, the partial boundary
        block by the boundary sub-hash; the mamba "align" boundary block is
        the core-provided CoW block. All keys are deduped against the store.

        Returns:
            True when no put is needed or every put succeeds, False otherwise.
        """
        if not self.coord.enable_partial_hash_hits or not req_meta.block_hashes:
            return True
        partial_tail_offloads = req_meta.partial_tail_offloads
        if not partial_tail_offloads:
            return True
        hash_block_size = self.coord.hash_block_size
        boundaries = {boundary for _, _, boundary in partial_tail_offloads}
        if len(boundaries) != 1:
            raise ValueError(
                "Partial-tail offloads for one request must share a boundary"
            )
        boundary = boundaries.pop()
        if boundary == 0:
            return True
        if boundary // hash_block_size - 1 >= len(req_meta.block_hashes):
            return True
        mamba_offloads = {
            group_id: block_id for group_id, block_id, _ in partial_tail_offloads
        }

        keys: list[str] = []
        addrs: list[list[int]] = []
        sizes: list[list[int]] = []
        group_ids: list[str] | None = (
            [] if self.enable_group_semantics and self.supports_group_ids else None
        )
        saved = self._saved_offset.get(req_meta.req_id, 0)
        for g_idx, db in enumerate(self.token_databases):
            group_blocks = req_meta.block_ids[g_idx]
            # Distribute across ranks by the same rule as normal chunks.
            put_step = self.group_put_steps[g_idx]
            put_step_rank = (self.tp_rank + g_idx) % put_step
            # Always include the boundary block: its sub-hash key is written
            # only here, even if normal saves already advanced past it.
            last_block = cdiv(boundary, db.block_size) - 1
            for block_idx in range(
                min(saved // db.block_size, last_block), last_block + 1
            ):
                if block_idx % put_step != put_step_rank:
                    continue
                valid_end = min((block_idx + 1) * db.block_size, boundary)
                key_hash = req_meta.block_hashes[valid_end // hash_block_size - 1]
                if (
                    g_idx in mamba_offloads
                    and valid_end == boundary
                    and boundary % db.block_size != 0
                ):
                    block_id = mamba_offloads[g_idx]
                else:
                    if block_idx >= len(group_blocks):
                        continue
                    block_id = group_blocks[block_idx]
                if block_id == NULL_BLOCK_ID:
                    logger.debug(
                        "Skipping unavailable partial-tail source block "
                        "(req=%s, group=%d, block=%d)",
                        req_meta.req_id,
                        g_idx,
                        block_idx,
                    )
                    continue
                addr, size = db.prepare_value_for_block(block_id)
                key = db.key_for(key_hash)
                keys.append(key)
                addrs.append(addr)
                sizes.append(size)
                if group_ids is not None:
                    group_ids.append(
                        _make_mooncake_group_id(
                            db.metadata,
                            key.rsplit("@", 1)[-1],
                        )
                    )

        if not keys:
            return True
        exists_start = time.perf_counter()
        try:
            exists = self.store.batch_is_exist(keys)
        except Exception as e:
            self._record_operation(
                "save_exists",
                exists_start,
                len(keys),
                status="error",
                num_failed_keys=len(keys),
            )
            logger.error(
                "Failed to check partial-tail keys for request %s: %s",
                req_meta.req_id,
                e,
            )
            return False
        self._record_operation("save_exists", exists_start, len(keys))
        missing = [i for i, e in enumerate(exists) if e != 1]
        if not missing:
            return True
        keys = [keys[i] for i in missing]
        addrs = [addrs[i] for i in missing]
        sizes = [sizes[i] for i in missing]
        if group_ids is not None:
            group_ids = [group_ids[i] for i in missing]
        if req_meta.current_event is not None:
            # Fence the CoW block copy enqueued earlier this step.
            req_meta.current_event.synchronize()
        if group_ids is not None:
            assert len(group_ids) == len(keys)
            self.replicate_config.group_ids = group_ids
        batch_bytes = _sum_batch_bytes(sizes)
        put_start = time.perf_counter()
        try:
            res = self.store.batch_put_from_multi_buffers(
                keys, addrs, sizes, self.replicate_config
            )
        except Exception as e:
            self._record_operation(
                "save_put",
                put_start,
                len(keys),
                num_bytes=batch_bytes,
                status="error",
                num_failed_keys=len(keys),
            )
            logger.error(
                "Failed to put partial-tail keys for request %s: %s",
                req_meta.req_id,
                e,
            )
            return False

        failed = [i for i, value in enumerate(res) if value < 0]
        self._record_operation(
            "save_put",
            put_start,
            len(keys),
            num_bytes=batch_bytes,
            status="partial_failure" if failed else "ok",
            num_failed_keys=len(failed),
        )
        if failed:
            failed_codes = {res[i] for i in failed}
            logger.warning(
                "Partial-tail put failed for request %s: %d/%d keys failed (codes=%s)",
                req_meta.req_id,
                len(failed),
                len(keys),
                failed_codes,
            )
            if MOONCAKE_NO_AVAILABLE_HANDLE in failed_codes:
                self._mark_request_skipped_for_pressure(req_meta.req_id)
            return False

        if self._clear_store_pressure():
            logger.info(
                "Mooncake CPU/disk offloading pressure cleared after a "
                "successful partial-tail batch"
            )
        return True

    def _handle_request(self, req_meta: ReqMeta):
        # Cache hits are always a multiple of ``lcm_block_size`` tokens, which
        # is also ``store_mask``'s precondition.
        lcm_block_size = self.coord.lcm_block_size
        token_len = req_meta.token_len_chunk // lcm_block_size * lcm_block_size
        block_ids_per_group = req_meta.block_ids
        req_id = req_meta.req_id
        current_event = req_meta.current_event

        if req_id not in self.stored_requests:
            self.request_queue.task_done()
            return

        # Decrement the in-flight counter and signal task_done() in `finally`
        # so the scheduler can release the GPU blocks it pinned for this
        # request (via `delay_free_blocks`) even when the store path raises.
        try:
            if self._should_skip_request(req_id):
                logger.debug(
                    "Skipping Mooncake store for request %s while CPU/disk "
                    "offloading is under pressure",
                    req_id,
                )
                return

            # Offload the sub-block partial tail (independent of the normal
            # block-aligned save, which may be skipped this step).
            if req_meta.partial_tail_offloads is not None and not (
                self._maybe_offload_partial_tail(req_meta)
            ):
                return

            if token_len == 0:
                return

            # Resume from where this rank left off; only the new suffix is saved.
            save_start = self._saved_offset.get(req_id, 0)

            # Within each lcm region only per-spec relevant chunks are loaded
            # (e.g., SWA or linear attn), so mask out irrelevant chunks
            store_masks = self.coord.store_mask(
                token_len,
                save_start,
                num_prompt_tokens=req_meta.num_prompt_tokens,
            )

            starts: list[int] = []
            ends: list[int] = []
            keys: list[str] = []
            kv_event_block_hashes: list[BlockHash] = []
            group_indices: list[int] = []
            for g_idx, db in enumerate(self.token_databases):
                # Rotate the stride phase per group to balance load across ranks.
                put_step = self.group_put_steps[g_idx]
                put_step_rank = (self.tp_rank + g_idx) % put_step
                for start, end, block_hash in db.process_tokens(
                    token_len,
                    req_meta.block_hashes,
                    mask_num=save_start,
                    chunk_mask=store_masks[g_idx],
                    put_step=put_step,
                    put_step_rank=put_step_rank,
                ):
                    starts.append(start)
                    ends.append(end)
                    keys.append(db.key_for(block_hash))
                    if self.enable_kv_event:
                        kv_event_block_hashes.append(block_hash)
                    group_indices.append(g_idx)

            if not keys:
                self._record_saved(req_id, token_len)
                return

            # Check which blocks already exist (dedup)
            save_exists_start = time.perf_counter()
            try:
                exists_states = self.store.batch_is_exist(keys)
            except Exception:
                self._record_operation(
                    "save_exists",
                    save_exists_start,
                    len(keys),
                    status="error",
                    num_failed_keys=len(keys),
                )
                raise
            self._record_operation(
                "save_exists",
                save_exists_start,
                len(keys),
            )
            missing_indices = [
                i for i, exists in enumerate(exists_states) if exists != 1
            ]

            if not missing_indices:
                self._record_saved(req_id, token_len)
                return

            if len(missing_indices) != len(keys):
                starts = [starts[i] for i in missing_indices]
                ends = [ends[i] for i in missing_indices]
                keys = [keys[i] for i in missing_indices]
                if self.enable_kv_event:
                    kv_event_block_hashes = [
                        kv_event_block_hashes[i] for i in missing_indices
                    ]
                group_indices = [group_indices[i] for i in missing_indices]

            group_ids = (
                [
                    _make_mooncake_group_id(
                        self.token_databases[g_idx].metadata,
                        key.rsplit("@", 1)[-1],
                    )
                    for key, g_idx in zip(keys, group_indices, strict=True)
                ]
                if self.enable_group_semantics and self.supports_group_ids
                else None
            )

            logger.debug(
                "Storing KV cache for %d blocks (groups=%s) for request %s",
                len(keys),
                set(group_indices),
                req_id,
            )

            addrs: list[list[int]] = []
            sizes: list[list[int]] = []
            stored_events: list[BlockStored] = []
            chunks_per_group: list[list[tuple[int, int]]] = [
                [] for _ in self.token_databases
            ]
            for start, end, g_idx in zip(starts, ends, group_indices, strict=True):
                chunks_per_group[g_idx].append((start, end))
            for g_idx, chunks in enumerate(chunks_per_group):
                if not chunks:
                    continue
                db = self.token_databases[g_idx]
                group_addrs, group_sizes, _ = db.prepare_values(
                    chunks, block_ids_per_group[g_idx]
                )
                addrs.extend(group_addrs)
                sizes.extend(group_sizes)

            # parent_block_hash chains live within a group, not across.
            if self.enable_kv_event:
                prev_key_per_group: dict[int, Any] = {}
                new_block_hashes = [
                    maybe_convert_block_hash(bh) for bh in kv_event_block_hashes
                ]

            for idx, (s, e, g_idx) in enumerate(
                zip(starts, ends, group_indices, strict=True)
            ):
                db = self.token_databases[g_idx]
                if self.enable_kv_event:
                    token_ids = (
                        req_meta.token_ids[s:e]
                        if req_meta.token_ids is not None
                        else None
                    )
                    stored_event = BlockStored(
                        block_hashes=[new_block_hashes[idx]],
                        parent_block_hash=prev_key_per_group.get(g_idx),
                        token_ids=token_ids,
                        block_size=db.block_size,
                        lora_id=None,
                        medium="cpu",
                        lora_name=None,
                        group_idx=g_idx,
                    )
                    stored_events.append(stored_event)
                    prev_key_per_group[g_idx] = new_block_hashes[idx]

            if current_event is not None:
                current_event.synchronize()

            if group_ids is not None:
                assert len(group_ids) == len(keys)
                self.replicate_config.group_ids = group_ids

            batch_bytes = _sum_batch_bytes(sizes)
            put_start = time.perf_counter()
            try:
                res = self.store.batch_put_from_multi_buffers(
                    keys,
                    addrs,
                    sizes,
                    self.replicate_config,
                )
                failed = [i for i, v in enumerate(res) if v < 0]
                self._record_operation(
                    "save_put",
                    put_start,
                    len(keys),
                    num_bytes=batch_bytes,
                    status="partial_failure" if failed else "ok",
                    num_failed_keys=len(failed),
                )
                if failed:
                    failed_codes = set(res[i] for i in failed)
                    logger.warning(
                        "batch_put failed: %d/%d keys failed "
                        "(codes=%s, batch_bytes=%d, num_keys=%d), "
                        "first_key=%s",
                        len(failed),
                        len(keys),
                        failed_codes,
                        batch_bytes,
                        len(keys),
                        keys[0] if keys else "N/A",
                    )
                    if (
                        MOONCAKE_NO_AVAILABLE_HANDLE in failed_codes
                        and not self._mark_request_skipped_for_pressure(req_id)
                    ):
                        logger.warning(
                            "Detected Mooncake CPU/disk offloading pressure "
                            "(NO_AVAILABLE_HANDLE); skipping future store "
                            "batches for request %s until a later store "
                            "batch succeeds",
                            req_id,
                        )
                else:
                    self._record_saved(req_id, token_len)
                    if self._clear_store_pressure():
                        logger.info(
                            "Mooncake CPU/disk offloading pressure cleared "
                            "after a successful store batch"
                        )
            except Exception as e:
                self._record_operation(
                    "save_put",
                    put_start,
                    len(keys),
                    num_bytes=batch_bytes,
                    status="error",
                    num_failed_keys=len(keys),
                )
                logger.error("Failed to put key %s, error: %s", keys, e)

            if self.enable_kv_event and stored_events:
                self.update_kv_event(stored_events)
        finally:
            self.dec_stored_request(req_id)
            self.request_queue.task_done()

_maybe_offload_partial_tail(req_meta)

Offload the request's sub-block partial tail (its last prompt hash boundary) so a later request can hit the sub-block prefix.

Covers every block from the normal save's lcm floor to the boundary: the normal save floors to lcm_block_size, so a smaller-block group's full blocks in that gap are never persisted elsewhere, and the consumer's lookup needs every group at every probed boundary. Full blocks are keyed by their block-end hash, the partial boundary block by the boundary sub-hash; the mamba "align" boundary block is the core-provided CoW block. All keys are deduped against the store.

Returns:

  • bool

    True when no put is needed or every put succeeds, False otherwise.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
def _maybe_offload_partial_tail(self, req_meta: ReqMeta) -> bool:
    """Offload the request's sub-block partial tail (its last prompt hash
    boundary) so a later request can hit the sub-block prefix.

    Covers every block from the normal save's lcm floor to the boundary:
    the normal save floors to ``lcm_block_size``, so a smaller-block
    group's full blocks in that gap are never persisted elsewhere, and
    the consumer's lookup needs every group at every probed boundary.
    Full blocks are keyed by their block-end hash, the partial boundary
    block by the boundary sub-hash; the mamba "align" boundary block is
    the core-provided CoW block. All keys are deduped against the store.

    Returns:
        True when no put is needed or every put succeeds, False otherwise.
    """
    if not self.coord.enable_partial_hash_hits or not req_meta.block_hashes:
        return True
    partial_tail_offloads = req_meta.partial_tail_offloads
    if not partial_tail_offloads:
        return True
    hash_block_size = self.coord.hash_block_size
    boundaries = {boundary for _, _, boundary in partial_tail_offloads}
    if len(boundaries) != 1:
        raise ValueError(
            "Partial-tail offloads for one request must share a boundary"
        )
    boundary = boundaries.pop()
    if boundary == 0:
        return True
    if boundary // hash_block_size - 1 >= len(req_meta.block_hashes):
        return True
    mamba_offloads = {
        group_id: block_id for group_id, block_id, _ in partial_tail_offloads
    }

    keys: list[str] = []
    addrs: list[list[int]] = []
    sizes: list[list[int]] = []
    group_ids: list[str] | None = (
        [] if self.enable_group_semantics and self.supports_group_ids else None
    )
    saved = self._saved_offset.get(req_meta.req_id, 0)
    for g_idx, db in enumerate(self.token_databases):
        group_blocks = req_meta.block_ids[g_idx]
        # Distribute across ranks by the same rule as normal chunks.
        put_step = self.group_put_steps[g_idx]
        put_step_rank = (self.tp_rank + g_idx) % put_step
        # Always include the boundary block: its sub-hash key is written
        # only here, even if normal saves already advanced past it.
        last_block = cdiv(boundary, db.block_size) - 1
        for block_idx in range(
            min(saved // db.block_size, last_block), last_block + 1
        ):
            if block_idx % put_step != put_step_rank:
                continue
            valid_end = min((block_idx + 1) * db.block_size, boundary)
            key_hash = req_meta.block_hashes[valid_end // hash_block_size - 1]
            if (
                g_idx in mamba_offloads
                and valid_end == boundary
                and boundary % db.block_size != 0
            ):
                block_id = mamba_offloads[g_idx]
            else:
                if block_idx >= len(group_blocks):
                    continue
                block_id = group_blocks[block_idx]
            if block_id == NULL_BLOCK_ID:
                logger.debug(
                    "Skipping unavailable partial-tail source block "
                    "(req=%s, group=%d, block=%d)",
                    req_meta.req_id,
                    g_idx,
                    block_idx,
                )
                continue
            addr, size = db.prepare_value_for_block(block_id)
            key = db.key_for(key_hash)
            keys.append(key)
            addrs.append(addr)
            sizes.append(size)
            if group_ids is not None:
                group_ids.append(
                    _make_mooncake_group_id(
                        db.metadata,
                        key.rsplit("@", 1)[-1],
                    )
                )

    if not keys:
        return True
    exists_start = time.perf_counter()
    try:
        exists = self.store.batch_is_exist(keys)
    except Exception as e:
        self._record_operation(
            "save_exists",
            exists_start,
            len(keys),
            status="error",
            num_failed_keys=len(keys),
        )
        logger.error(
            "Failed to check partial-tail keys for request %s: %s",
            req_meta.req_id,
            e,
        )
        return False
    self._record_operation("save_exists", exists_start, len(keys))
    missing = [i for i, e in enumerate(exists) if e != 1]
    if not missing:
        return True
    keys = [keys[i] for i in missing]
    addrs = [addrs[i] for i in missing]
    sizes = [sizes[i] for i in missing]
    if group_ids is not None:
        group_ids = [group_ids[i] for i in missing]
    if req_meta.current_event is not None:
        # Fence the CoW block copy enqueued earlier this step.
        req_meta.current_event.synchronize()
    if group_ids is not None:
        assert len(group_ids) == len(keys)
        self.replicate_config.group_ids = group_ids
    batch_bytes = _sum_batch_bytes(sizes)
    put_start = time.perf_counter()
    try:
        res = self.store.batch_put_from_multi_buffers(
            keys, addrs, sizes, self.replicate_config
        )
    except Exception as e:
        self._record_operation(
            "save_put",
            put_start,
            len(keys),
            num_bytes=batch_bytes,
            status="error",
            num_failed_keys=len(keys),
        )
        logger.error(
            "Failed to put partial-tail keys for request %s: %s",
            req_meta.req_id,
            e,
        )
        return False

    failed = [i for i, value in enumerate(res) if value < 0]
    self._record_operation(
        "save_put",
        put_start,
        len(keys),
        num_bytes=batch_bytes,
        status="partial_failure" if failed else "ok",
        num_failed_keys=len(failed),
    )
    if failed:
        failed_codes = {res[i] for i in failed}
        logger.warning(
            "Partial-tail put failed for request %s: %d/%d keys failed (codes=%s)",
            req_meta.req_id,
            len(failed),
            len(keys),
            failed_codes,
        )
        if MOONCAKE_NO_AVAILABLE_HANDLE in failed_codes:
            self._mark_request_skipped_for_pressure(req_meta.req_id)
        return False

    if self._clear_store_pressure():
        logger.info(
            "Mooncake CPU/disk offloading pressure cleared after a "
            "successful partial-tail batch"
        )
    return True

KVTransferThread

Bases: Thread

Base class for async KV cache transfer threads.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
class KVTransferThread(threading.Thread):
    """Base class for async KV cache transfer threads."""

    def __init__(
        self,
        store: Any,
        token_databases: list[ChunkedTokenDatabase],
        block_size: int,
        tp_rank: int,
        ready_event: threading.Event,
        name: str,
        record_operation: Callable[..., None] | None = None,
        request_queue: queue.Queue[Any] | None = None,
    ):
        super().__init__(daemon=True, name=name)
        self.store = store
        self.ready_event = ready_event
        self.block_size = block_size
        self.tp_rank = tp_rank
        self.token_databases = token_databases
        self._record_operation_cb = record_operation
        self.done_task_lock = threading.Lock()
        self.request_queue: queue.Queue[Any] = request_queue or queue.Queue()
        self.finished_requests: set[str] = set()
        self.kv_event_lock = threading.Lock()
        self.kv_events: list[BlockStored] = []

    def add_request(self, request: ReqMeta) -> None:
        self.request_queue.put(request)

    def get_and_clear_finished_requests(self) -> set[str]:
        with self.done_task_lock:
            finished = self.finished_requests.copy()
            self.finished_requests.clear()
        return finished

    def set_finished_request(self, req_id: str):
        with self.done_task_lock:
            self.finished_requests.add(req_id)

    def run(self):
        self.ready_event.set()
        while True:
            request_data = None
            try:
                request_data = self.request_queue.get()
                if request_data is None:
                    logger.warning("Received a None request!")
                    self.request_queue.task_done()
                    continue
                self._handle_request(request_data)
            except Exception:
                req_id = getattr(request_data, "req_id", "<unknown>")
                logger.exception("Error in %s (req=%s)", self.name, req_id)

    def _handle_request(self, req_meta: Any):
        pass

    def _record_operation(
        self,
        operation: str,
        start_time: float,
        num_keys: int,
        *,
        num_bytes: int = 0,
        status: str = "ok",
        num_failed_keys: int = 0,
    ) -> None:
        if self._record_operation_cb is None:
            return
        self._record_operation_cb(
            operation=operation,
            duration_seconds=time.perf_counter() - start_time,
            num_keys=num_keys,
            num_bytes=num_bytes,
            status=status,
            num_failed_keys=num_failed_keys,
        )

    def update_kv_event(self, events: list[BlockStored]):
        with self.kv_event_lock:
            self.kv_events.extend(events)

    def get_kv_events(self) -> list[BlockStored]:
        with self.kv_event_lock:
            events = self.kv_events.copy()
            self.kv_events.clear()
        return events

LookupKeyClient

ZMQ client for the LookupKey admin channel.

Routes both prefix-cache lookups and admin commands (currently: reset) to LookupKeyServer on worker rank 0. The first frame of every request is a named tag from protocol.py.

Methods:

  • discard

    Drop any cached/in-flight lookup for req_id (e.g. on abort).

  • lookup

    If non_block is True, will return None until the result is ready,

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
class LookupKeyClient:
    """ZMQ client for the LookupKey admin channel.

    Routes both prefix-cache lookups and admin commands (currently:
    ``reset``) to ``LookupKeyServer`` on worker rank 0. The first frame
    of every request is a named tag from ``protocol.py``.
    """

    def __init__(self, vllm_config: VllmConfig):
        self.ctx = zmq.Context()  # type: ignore[attr-defined]
        socket_path = get_zmq_rpc_path_lookup(vllm_config)
        self.socket = make_zmq_socket(
            self.ctx,
            socket_path,
            zmq.REQ,  # type: ignore[attr-defined]
            bind=False,
        )

        # Async lookup support
        self.executor = ThreadPoolExecutor(
            max_workers=1, thread_name_prefix="MooncakeLookupClient"
        )
        self.futures: dict[str, Future[int]] = {}

    def _lookup(self, num_tokens: int, block_hashes: list[BlockHash]) -> int:
        hash_len = len(block_hashes[0]) if block_hashes else 0
        all_frames = (
            LOOKUP_MSG,
            num_tokens.to_bytes(4, byteorder="big"),
            hash_len.to_bytes(2, byteorder="big"),
            b"".join(block_hashes),
        )
        self.socket.send_multipart(all_frames, copy=False)
        resp = self.socket.recv()
        return int.from_bytes(resp, "big")

    def lookup(
        self,
        req_id: str,
        num_tokens: int,
        block_hashes: list[BlockHash],
        non_block: bool = False,
    ) -> int | None:
        """If non_block is True, will return None until the result is ready,
        so the caller retries on a later step."""
        future = self.futures.get(req_id)
        if future is None:
            future = self.executor.submit(self._lookup, num_tokens, list(block_hashes))
            self.futures[req_id] = future
        if non_block and not future.done():
            return None
        try:
            return future.result()
        except Exception as e:
            logger.error("Async Mooncake lookup failed for %s: %s", req_id, e)
            return 0
        finally:
            del self.futures[req_id]

    def discard(self, req_id: str) -> None:
        """Drop any cached/in-flight lookup for ``req_id`` (e.g. on abort)."""
        future = self.futures.pop(req_id, None)
        if future is not None:
            future.cancel()

    def _reset(self) -> bool:
        """Trigger ``store.remove_all(force=True)`` on worker rank 0.

        Ordering assumption: caller MUST ensure no in-flight Mooncake
        lookups or transfers when invoking reset. In RL workflows this
        holds naturally at the step boundary after weight updates and
        rollout drain. Returns True on ACK, False on NACK.
        """
        self.socket.send(RESET_MSG)
        resp = self.socket.recv()
        return bytes(resp) == RESP_OK

    def reset(self) -> bool:
        return self.executor.submit(self._reset).result()

    def close(self):
        self.executor.shutdown(wait=False, cancel_futures=True)
        self.socket.close(linger=0)

_reset()

Trigger store.remove_all(force=True) on worker rank 0.

Ordering assumption: caller MUST ensure no in-flight Mooncake lookups or transfers when invoking reset. In RL workflows this holds naturally at the step boundary after weight updates and rollout drain. Returns True on ACK, False on NACK.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
def _reset(self) -> bool:
    """Trigger ``store.remove_all(force=True)`` on worker rank 0.

    Ordering assumption: caller MUST ensure no in-flight Mooncake
    lookups or transfers when invoking reset. In RL workflows this
    holds naturally at the step boundary after weight updates and
    rollout drain. Returns True on ACK, False on NACK.
    """
    self.socket.send(RESET_MSG)
    resp = self.socket.recv()
    return bytes(resp) == RESP_OK

discard(req_id)

Drop any cached/in-flight lookup for req_id (e.g. on abort).

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
def discard(self, req_id: str) -> None:
    """Drop any cached/in-flight lookup for ``req_id`` (e.g. on abort)."""
    future = self.futures.pop(req_id, None)
    if future is not None:
        future.cancel()

lookup(req_id, num_tokens, block_hashes, non_block=False)

If non_block is True, will return None until the result is ready, so the caller retries on a later step.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
def lookup(
    self,
    req_id: str,
    num_tokens: int,
    block_hashes: list[BlockHash],
    non_block: bool = False,
) -> int | None:
    """If non_block is True, will return None until the result is ready,
    so the caller retries on a later step."""
    future = self.futures.get(req_id)
    if future is None:
        future = self.executor.submit(self._lookup, num_tokens, list(block_hashes))
        self.futures[req_id] = future
    if non_block and not future.done():
        return None
    try:
        return future.result()
    except Exception as e:
        logger.error("Async Mooncake lookup failed for %s: %s", req_id, e)
        return 0
    finally:
        del self.futures[req_id]

LookupKeyServer

ZMQ server on worker rank 0 for the LookupKey admin channel.

Handles two request types, tagged at frame 0: - LOOKUP_MSG: prefix-cache hit query, returns hit count. - RESET_MSG: drains the send thread queue, then runs store.remove_all(force=True). Caller must have paused the scheduler first.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
class LookupKeyServer:
    """ZMQ server on worker rank 0 for the LookupKey admin channel.

    Handles two request types, tagged at frame 0:
    - ``LOOKUP_MSG``: prefix-cache hit query, returns hit count.
    - ``RESET_MSG``: drains the send thread queue, then runs
      ``store.remove_all(force=True)``. Caller must have paused the
      scheduler first.
    """

    def __init__(
        self,
        store_worker: MooncakeStoreWorker,
        vllm_config: VllmConfig,
    ):
        self.ctx = zmq.Context()  # type: ignore[attr-defined]
        socket_path = get_zmq_rpc_path_lookup(vllm_config)
        self._ipc_path = socket_path.removeprefix("ipc://")
        if os.path.exists(self._ipc_path):
            os.unlink(self._ipc_path)
        self.socket = make_zmq_socket(
            self.ctx,
            socket_path,
            zmq.REP,  # type: ignore[attr-defined]
            bind=True,
        )

        self.store_worker = store_worker
        self.running = True

        def process_request():
            while self.running:
                all_frames = self.socket.recv_multipart(copy=False)
                msg_type = bytes(all_frames[0])

                if msg_type == LOOKUP_MSG:
                    num_tokens = int.from_bytes(all_frames[1], byteorder="big")
                    hash_len = int.from_bytes(all_frames[2], byteorder="big")
                    blob = all_frames[3].buffer
                    block_hashes = BlobBlockHashes(blob, hash_len)
                    result = self.store_worker.lookup(num_tokens, block_hashes)
                    self.socket.send(result.to_bytes(4, "big"))

                elif msg_type == RESET_MSG:
                    try:
                        # Drain in-flight puts before wiping the master;
                        # otherwise stale puts can repopulate it post-reset.
                        # Safe across HMA: store.remove_all wipes the underlying
                        # flat key space, clearing every (group_id, hash) entry.
                        if self.store_worker.kv_send_thread is not None:
                            self.store_worker.kv_send_thread.request_queue.join()
                        self.store_worker.store.remove_all(force=True)
                        logger.info("Mooncake store reset via remove_all succeeded.")
                        self.socket.send(RESP_OK)
                    except Exception as e:
                        logger.error("Mooncake remove_all failed: %s", e)
                        self.socket.send(RESP_ERR)

                else:
                    logger.warning(
                        "LookupKeyServer received unknown msg_type: %r",
                        msg_type,
                    )
                    self.socket.send(RESP_ERR)

        self.thread = threading.Thread(target=process_request, daemon=True)
        self.thread.start()

    def close(self):
        self.socket.close(linger=0)
        if os.path.exists(self._ipc_path):
            os.unlink(self._ipc_path)

MooncakeStoreConfig dataclass

Configuration for MooncakeDistributedStore.

mode selects the topology: embedded (each rank contributes global_segment_size in-process) or standalone-store (rank contributes 0; an external mooncake_client process owns the pool and the SSD tier).

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
@dataclass
class MooncakeStoreConfig:
    """Configuration for MooncakeDistributedStore.

    ``mode`` selects the topology: ``embedded`` (each rank contributes
    ``global_segment_size`` in-process) or ``standalone-store`` (rank
    contributes 0; an external ``mooncake_client`` process owns the pool
    and the SSD tier).
    """

    metadata_server: str
    master_server_address: str
    protocol: str
    device_name: str
    mode: MooncakeMode = "embedded"
    global_segment_size: int = DEFAULT_GLOBAL_SEGMENT_SIZE
    local_buffer_size: int = DEFAULT_LOCAL_BUFFER_SIZE
    enable_offload: bool = False
    tenant_id: str = DEFAULT_TENANT_ID

    def __post_init__(self) -> None:
        if self.mode not in ("embedded", "standalone-store"):
            raise ValueError(f"unknown Mooncake mode: {self.mode!r}")
        if self.local_buffer_size <= 0:
            raise ValueError("local_buffer_size must be > 0")
        if self.mode == "embedded" and self.global_segment_size == 0:
            raise ValueError("embedded mode requires global_segment_size > 0")
        if self.mode == "standalone-store" and self.global_segment_size != 0:
            raise ValueError("standalone-store mode requires global_segment_size == 0")

    @staticmethod
    def from_file(file_path: str) -> "MooncakeStoreConfig":
        with open(file_path) as file:
            config = json.load(file)
        return MooncakeStoreConfig(
            metadata_server=config.get("metadata_server", ""),
            master_server_address=config.get("master_server_address", ""),
            protocol=config.get("protocol", "rdma"),
            device_name=config.get("device_name", ""),
            mode=config.get("mode", "embedded"),
            global_segment_size=_parse_size(
                config.get("global_segment_size", DEFAULT_GLOBAL_SEGMENT_SIZE)
            ),
            local_buffer_size=_parse_size(
                config.get("local_buffer_size", DEFAULT_LOCAL_BUFFER_SIZE)
            ),
            enable_offload=bool(config.get("enable_offload", False)),
            tenant_id=_normalize_tenant_id(config.get("tenant_id", DEFAULT_TENANT_ID)),
        )

    @staticmethod
    def load_from_config() -> "MooncakeStoreConfig":
        config_path = os.getenv("MOONCAKE_CONFIG_PATH")
        if not config_path:
            raise ValueError(
                "The environment variable 'MOONCAKE_CONFIG_PATH' is not set."
            )
        return MooncakeStoreConfig.from_file(config_path)

MooncakeStoreWorker

Worker-side component for MooncakeStoreConnector.

Methods:

  • close

    Release the MooncakeDistributedStore handle on teardown.

  • get_finished

    Issue all I/O and get completed send/recv request IDs.

  • lookup

    Check how many prefix tokens exist in the store.

  • register_cross_layers_kv_caches

    Register a cross-layers KV cache tensor.

  • register_kv_caches

    Register KV cache tensors and start transfer threads.

  • start_load_kv

    No-op: loads are issued in get_finished() for overlap.

  • wait_for_save

    No-op: stores are issued in get_finished() for overlap.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
class MooncakeStoreWorker:
    """Worker-side component for MooncakeStoreConnector."""

    def __init__(
        self,
        vllm_config: VllmConfig,
        kv_cache_config: KVCacheConfig,
    ):
        try:
            from mooncake.store import (  # type: ignore
                MooncakeDistributedStore,
                ReplicateConfig,
            )
        except ImportError as e:
            raise ImportError(
                "Please install mooncake by following the instructions at "
                "https://github.com/kvcache-ai/Mooncake/blob/main/doc/"
                "en/build.md to run vLLM with MooncakeStoreConnector."
            ) from e

        model_config = vllm_config.model_config
        parallel_config = vllm_config.parallel_config

        self.dp_rank = parallel_config.data_parallel_index
        self.tp_rank = get_tensor_model_parallel_rank()
        self.tp_size = get_tensor_model_parallel_world_size()
        self.pp_size = parallel_config.pipeline_parallel_size
        self.pp_rank = (parallel_config.rank // self.tp_size) % self.pp_size

        self.pcp_size = get_pcp_group().world_size
        self.pcp_rank = get_pcp_group().rank_in_group if self.pcp_size > 1 else 0
        self.dcp_size = get_dcp_group().world_size
        self.dcp_rank = get_dcp_group().rank_in_group if self.dcp_size > 1 else 0

        assert vllm_config.kv_transfer_config is not None
        self.kv_role = vllm_config.kv_transfer_config.kv_role
        self.load_async = vllm_config.kv_transfer_config.kv_connector_extra_config.get(
            "load_async", True
        )
        # Mirrors MooncakeStoreConnector._capacity_only.
        self._capacity_only = self.kv_role == "kv_consumer" and not (
            vllm_config.kv_transfer_config.kv_connector_extra_config.get(
                "enable_lookup", True
            )
        )
        self.cache_config = vllm_config.cache_config
        self.block_size, self.hash_block_size = resolve_kv_cache_block_sizes(
            kv_cache_config, vllm_config
        )
        self.num_layers = model_config.get_num_layers(parallel_config)

        self.num_kv_head = model_config.get_total_num_kv_heads()

        # Initialize MooncakeDistributedStore with its own TransferEngine
        store_config = MooncakeStoreConfig.load_from_config()
        extra_config = (
            vllm_config.kv_transfer_config.kv_connector_extra_config
            if vllm_config.kv_transfer_config
            else {}
        )
        self.store = MooncakeDistributedStore()
        local_ip = get_ip()
        local_hostname = rdma_utils.get_requester_local_hostname(local_ip)
        setup_kwargs: dict[str, str] = {}
        if store_config.tenant_id != DEFAULT_TENANT_ID:
            setup_kwargs["tenant_id"] = store_config.tenant_id
        ret = self.store.setup(
            local_hostname,
            store_config.metadata_server,
            store_config.global_segment_size,
            store_config.local_buffer_size,
            store_config.protocol,
            store_config.device_name,
            store_config.master_server_address,
            **setup_kwargs,
        )
        if ret != 0:
            msg = "Initialize MooncakeDistributedStore failed."
            logger.error(msg)
            raise RuntimeError(msg)

        preferred_segment = rdma_utils.get_configured_preferred_segment(extra_config)
        self.preferred_segment = preferred_segment
        self.store_replicate_config = ReplicateConfig()
        self.enable_group_semantics = (
            str(extra_config.get("enable_group_semantics", "False")).strip().lower()
            == "true"
        )
        self._supports_group_ids = _replicate_config_supports_group_ids(
            ReplicateConfig, self.store_replicate_config
        )
        if self.enable_group_semantics and not self._supports_group_ids:
            logger.warning(
                "Mooncake group semantics is enabled, but the installed "
                "Mooncake package does not support ReplicateConfig.group_ids. "
                "Falling back to the existing batch_put_from_multi_buffers path."
            )
        if preferred_segment is not None:
            self.store_replicate_config.preferred_segment = preferred_segment

        logger.info(
            "Mooncake mode=%s (global_segment_size=%d, local_buffer_size=%d, "
            "preferred_segment=%s, enable_offload=%s, tenant_id=%s)",
            store_config.mode,
            store_config.global_segment_size,
            store_config.local_buffer_size,
            preferred_segment or "<none>",
            store_config.enable_offload,
            store_config.tenant_id,
        )
        if store_config.mode == "embedded":
            if store_config.enable_offload and preferred_segment is None:
                logger.warning(
                    "enable_offload is set in embedded mode without "
                    "preferred_segment; SSD tier will only see puts that "
                    "happen to land on the owner segment."
                )
            if preferred_segment is not None:
                logger.warning(
                    "preferred_segment=%s with mode=embedded: rank-"
                    "contributed segments will be idle.",
                    preferred_segment,
                )
        elif (
            store_config.mode == "standalone-store" and not store_config.enable_offload
        ):
            logger.warning(
                "standalone-store mode without enable_offload: large prefills "
                "may exceed the owner DirectIO budget."
            )

        self.disk_offload_buffer_budget_bytes = (
            DEFAULT_MOONCAKE_DISK_STAGING_BUFFER_BYTES
            if store_config.enable_offload
            else None
        )

        # Start lookup server on rank 0 for scheduler-side prefix queries
        self.lookup_server: LookupKeyServer | None = None
        if vllm_config.parallel_config.rank == 0:
            self.lookup_server = LookupKeyServer(self, vllm_config)

        kv_event_config = vllm_config.kv_events_config
        self.enable_kv_events = False
        if kv_event_config and kv_event_config.enable_kv_cache_events:
            self.enable_kv_events = True

        self.kv_send_thread: KVCacheStoreSendingThread | None = None
        # Pool of load-receive threads
        self.kv_recv_threads: list[KVCacheStoreRecvingThread] = []
        self.num_recv_threads = max(1, envs.VLLM_MOONCAKE_LOAD_RECV_THREADS)
        self.recv_request_queue: queue.Queue[ReqMeta] = queue.Queue()
        self.finished_store_req: set[str] = set()
        self._kv_connector_stats_lock = threading.Lock()
        self.kv_connector_stats = MooncakeStoreConnectorStats()

        self._kv_cache_config = kv_cache_config
        self.token_dbs: list[ChunkedTokenDatabase] = []

        # a capacity-only instance does not need below utils
        if self._capacity_only:
            logger.info(
                "Mooncake store in capacity-only mode: segment mounted "
                "(global_segment_size=%d), KV transfer disabled.",
                store_config.global_segment_size,
            )
            return

        # Single-group + PCP/DCP > 1: scale the lone group's spec.block_size to
        # self.block_size (= scheduler_block_size) so the coordinator's
        # ``block_size % hash_block_size == 0`` invariant holds.
        groups = list(kv_cache_config.kv_cache_groups)
        if len(groups) == 1 and groups[0].kv_cache_spec.block_size != self.block_size:
            g = groups[0]
            groups = [
                dataclasses.replace(
                    g,
                    kv_cache_spec=dataclasses.replace(
                        g.kv_cache_spec, block_size=self.block_size
                    ),
                )
            ]
        self._kv_cache_groups: list[KVCacheGroupSpec] = groups
        spec_cfg = getattr(vllm_config, "speculative_config", None)
        use_eagle = bool(
            spec_cfg.use_eagle()
            if spec_cfg is not None and callable(getattr(spec_cfg, "use_eagle", None))
            else False
        )
        self.coord = MooncakeStoreCoordinator(
            self._kv_cache_groups,
            scheduler_block_size=self.block_size,
            hash_block_size=self.hash_block_size,
            use_eagle=use_eagle,
            retention_interval=envs.VLLM_PREFIX_CACHE_RETENTION_INTERVAL,
        )
        # One ChunkedTokenDatabase per group; addresses populated in
        # register_kv_caches once the kv-cache layout is known. Each group's
        # key namespace is its TP shard id: ranks holding identical bytes
        # (MLA / shared GQA KV heads) share a namespace, TP-sharded Mamba
        # state gets one namespace per rank.
        metadata = KeyMetadata(
            model_name=model_config.model.rstrip("/").split("/")[-1],
            tp_rank=self.tp_rank,
            pcp_rank=self.pcp_rank,
            dcp_rank=self.dcp_rank,
            pp_rank=self.pp_rank,
            cache_prefix=str(
                vllm_config.kv_transfer_config.kv_connector_extra_config.get(
                    "cache_prefix", ""
                )
            ),
        )
        self._group_tp_replication_factors: tuple[int, ...] = (
            self._compute_group_tp_replication_factors()
        )
        self.token_dbs = [
            ChunkedTokenDatabase(
                dataclasses.replace(
                    metadata,
                    group_id=g_idx,
                    tp_rank=self.tp_rank // self._group_tp_replication_factors[g_idx],
                ),
                g.kv_cache_spec.block_size,
                hash_block_size=self.hash_block_size,
            )
            for g_idx, g in enumerate(self._kv_cache_groups)
        ]
        self._init_lookup_key_prefixes()

    def _spec_tp_replication_factor(self, spec: KVCacheSpec) -> int:
        if self.dcp_size > 1:
            return 1
        inner_specs = (
            tuple(spec.kv_cache_specs.values())
            if isinstance(spec, UniformTypeKVCacheSpecs)
            else (spec,)
        )
        # Any rank-specific state makes the whole packed value rank-specific.
        if any(isinstance(inner, MambaSpec) for inner in inner_specs):
            return 1
        # A pure MLA packed value is replicated on every TP rank.
        if all(
            isinstance(inner, (MLAAttentionSpec, SlidingWindowMLASpec))
            for inner in inner_specs
        ):
            return self.tp_size
        return max(1, self.tp_size // self.num_kv_head)

    def _compute_group_tp_replication_factors(self) -> tuple[int, ...]:
        """Return the number of byte-identical TP replicas per cache group.

        DCP and Mamba use 1; MLA uses ``tp_size``; GQA uses
        ``tp_size // num_kv_head``.
        """
        return tuple(
            self._spec_tp_replication_factor(group.kv_cache_spec)
            for group in self._kv_cache_groups
        )

    def _init_lookup_key_prefixes(self) -> None:
        def rank_namespaces(factor: int) -> tuple[tuple[int, int, int, int], ...]:
            if self.dcp_size > 1:
                # DCP is a TP subdivision: dcp_rank == tp_rank % dcp_size.
                return tuple(
                    (tp_rank, pcp_rank, tp_rank % self.dcp_size, pp_rank)
                    for pcp_rank in range(self.pcp_size)
                    for tp_rank in range(self.tp_size)
                    for pp_rank in range(self.pp_size)
                )
            return tuple(
                (shard_rank, pcp_rank, 0, pp_rank)
                for pcp_rank in range(self.pcp_size)
                for shard_rank in range(self.tp_size // factor)
                for pp_rank in range(self.pp_size)
            )

        self._lookup_key_prefixes = tuple(
            tuple(
                PoolKey.build_prefix(
                    db.metadata,
                    tp_rank=tp_rank,
                    pcp_rank=pcp_rank,
                    dcp_rank=dcp_rank,
                    pp_rank=pp_rank,
                )
                for tp_rank, pcp_rank, dcp_rank, pp_rank in rank_namespaces(
                    self._group_tp_replication_factors[g_idx]
                )
            )
            for g_idx, db in enumerate(self.token_dbs)
        )

    def register_cross_layers_kv_caches(self, kv_cache: torch.Tensor) -> None:
        """Register a cross-layers KV cache tensor.

        Wraps the unified tensor in a single-entry dict so that the
        existing stride-based logic in register_kv_caches() produces
        the correct single-segment result (block_len = page_size * num_layers).
        """
        self.register_kv_caches({"__cross_layer__": kv_cache})

    def register_kv_caches(
        self,
        kv_caches: dict[str, torch.Tensor | list[torch.Tensor]],
    ) -> None:
        """Register KV cache tensors and start transfer threads."""
        if self._capacity_only:
            return
        if not kv_caches:
            logger.warning("No KV caches to offload.")
            return

        # Resolve each entry to a representative tensor for storage
        # deduplication. For attention layers the value is already a tensor;
        # for Mamba layers it is a list of tensors that all share the same
        # underlying raw storage, so we take the first one.
        def _repr_tensor(v: torch.Tensor | list[torch.Tensor]) -> torch.Tensor:
            assert isinstance(v, torch.Tensor | list)
            return v if isinstance(v, torch.Tensor) else v[0]

        assert self.cache_config.num_gpu_blocks is not None
        self.num_blocks = self.cache_config.num_gpu_blocks

        seen_ptrs: set[int] = set()
        addrs: list[int] = []
        block_lens: list[int] = []

        for value in kv_caches.values():
            cache = _repr_tensor(value)
            cache_storage = cache.untyped_storage()
            base_addr = cache_storage.data_ptr()
            if base_addr in seen_ptrs:
                continue
            seen_ptrs.add(base_addr)
            region_len = cache_storage.nbytes()

            ret = self.store.register_buffer(base_addr, region_len)
            if ret != 0:
                logger.error(
                    "register_buffer failed for addr %#x len %d: %d",
                    base_addr,
                    region_len,
                    ret,
                )

            # Detect layout via stride: a dim whose byte-stride exceeds
            # page_size_bytes is an outer segment dim (e.g. the K/V dim of
            # FlashAttn's (2, num_blocks, ...)). FlashInfer/MLA's blocks-
            # outermost layout has no such dim and yields a single segment.
            el = cache.element_size()
            page_size_bytes = region_len // self.num_blocks
            outer_dims = [
                d for d in range(cache.ndim) if cache.stride(d) * el > page_size_bytes
            ]
            if not outer_dims:
                # Blocks-first layout (FlashInfer / MLA): one segment.
                addrs.append(base_addr)
                block_lens.append(page_size_bytes)
            else:
                # K/V-first layout (FlashAttn / ROCm): split segments.
                seg_stride = cache.stride(outer_dims[0]) * el
                for idx in range(cache.shape[outer_dims[0]]):
                    addrs.append(base_addr + idx * seg_stride)
                    block_lens.append(seg_stride // self.num_blocks)

        logger.info(
            "Registered KV caches: num_groups=%d, num_segments=%d, num_blocks=%d",
            len(self.token_dbs),
            len(addrs),
            self.num_blocks,
        )

        for db in self.token_dbs:
            db.set_kv_caches_base_addr(addrs)
            db.set_block_len(block_lens)

        # Start transfer threads
        if self.kv_role in ["kv_producer", "kv_both"]:
            ready_event_sending = threading.Event()
            self.kv_send_thread = KVCacheStoreSendingThread(
                self.store,
                self.coord,
                self.token_dbs,
                self.block_size,
                self.tp_rank,
                self._group_tp_replication_factors,
                self.kv_role,
                ready_event_sending,
                self.enable_kv_events,
                self.store_replicate_config,
                enable_group_semantics=self.enable_group_semantics,
                supports_group_ids=self._supports_group_ids,
                record_operation=self._record_kv_connector_operation,
            )
            self.kv_send_thread.start()

        self.kv_recv_threads = []
        ready_events_recving = []
        for i in range(self.num_recv_threads):
            ready_event_recving = threading.Event()
            recv_thread = KVCacheStoreRecvingThread(
                self.store,
                self.coord,
                self.token_dbs,
                self.block_size,
                self.tp_rank,
                ready_event_recving,
                disk_offload_buffer_budget_bytes=self.disk_offload_buffer_budget_bytes,
                record_operation=self._record_kv_connector_operation,
                request_queue=self.recv_request_queue,
            )
            recv_thread.name = f"KVCacheStoreRecvingThread-{i}"
            recv_thread.start()
            self.kv_recv_threads.append(recv_thread)
            ready_events_recving.append(ready_event_recving)
        for ready_event_recving in ready_events_recving:
            ready_event_recving.wait()
        logger.info(
            "Started %d Mooncake KV-load receive thread(s)", self.num_recv_threads
        )

    def start_load_kv(
        self,
        metadata: MooncakeStoreConnectorMetadata,
    ):
        """No-op: loads are issued in get_finished() for overlap."""
        pass

    def wait_for_save(
        self,
        metadata: MooncakeStoreConnectorMetadata,
    ):
        """No-op: stores are issued in get_finished() for overlap."""
        pass

    def get_finished(
        self,
        finished_req_ids: set[str],
        meta: MooncakeStoreConnectorMetadata,
    ) -> tuple[set[str], set[str]]:
        """Issue all I/O and get completed send/recv request IDs.

        All load and store I/O requests are issued here (after model
        compute is launched on the compute stream) for better
        compute-I/O overlap.
        """
        if self._capacity_only:
            return set(), set()

        # Issue async loads
        for request in meta.requests:
            load_spec = request.load_spec
            if load_spec is None or not load_spec.can_load:
                continue

            load_spec.token_len = load_spec.kvpool_cached_tokens
            self.recv_request_queue.put(request)

        assert self.load_async, "load_async must be True for better performance."
        # Issue stores with CUDA event synchronization.
        if self.kv_role in ["kv_producer", "kv_both"]:
            current_event = None
            for request in meta.requests:
                if request.can_save:
                    current_event = torch.cuda.Event()
                    current_event.record()
                    break

            for request in meta.requests:
                if not request.can_save:
                    continue
                request.current_event = current_event
                assert self.kv_send_thread is not None
                self.kv_send_thread.add_stored_request(request.req_id)
                self.kv_send_thread.add_request(request)

        # Check completion of previously queued transfers
        done_sending = (
            self._get_and_clear_finished_sending(finished_req_ids, meta)
            if self.kv_role in ["kv_producer", "kv_both"]
            else set()
        )

        done_recving: set[str] = set()
        if self.load_async:
            for recv_thread in self.kv_recv_threads:
                done_recving |= recv_thread.get_and_clear_finished_requests()

        logger.debug(
            "Completed send: %d, recv: %d, tp_rank: %d",
            len(done_sending),
            len(done_recving),
            self.tp_rank,
        )
        return done_sending, done_recving

    def get_block_ids_with_load_errors(self) -> set[int]:
        block_ids: set[int] = set()
        for recv_thread in self.kv_recv_threads:
            block_ids |= recv_thread.get_and_clear_block_ids_with_load_errors()
        return block_ids

    def _record_kv_connector_operation(
        self,
        operation: str,
        duration_seconds: float,
        num_keys: int,
        *,
        num_bytes: int = 0,
        status: str = "ok",
        num_failed_keys: int = 0,
    ) -> None:
        with self._kv_connector_stats_lock:
            self.kv_connector_stats.record_operation(
                operation=operation,
                duration_seconds=duration_seconds,
                num_keys=num_keys,
                num_bytes=num_bytes,
                status=status,
                num_failed_keys=num_failed_keys,
            )

    def get_kv_connector_stats(self) -> MooncakeStoreConnectorStats | None:
        with self._kv_connector_stats_lock:
            if self.kv_connector_stats.is_empty():
                return None
            kv_connector_stats = self.kv_connector_stats
            self.kv_connector_stats = MooncakeStoreConnectorStats()
            return kv_connector_stats

    def _get_and_clear_finished_sending(
        self,
        finished_req_ids: set[str],
        meta: MooncakeStoreConnectorMetadata,
    ) -> set[str]:
        assert self.kv_send_thread is not None
        finished_sending: set[str] = set()

        for req_id in meta.preempted_req_ids:
            self.kv_send_thread.delete_finished_stored_request(req_id)

        for req_id in self.kv_send_thread.stored_requests.copy():
            if (
                self.kv_send_thread.stored_requests[req_id] == 0
                and req_id in self.finished_store_req
            ):
                self.finished_store_req.remove(req_id)
                finished_sending.add(req_id)
                self.kv_send_thread.delete_finished_stored_request(req_id)

        for req_id in finished_req_ids:
            req_remain_jobs = self.kv_send_thread.stored_requests.get(req_id)
            if req_remain_jobs == 0:
                finished_sending.add(req_id)
                self.kv_send_thread.delete_finished_stored_request(req_id)
            elif req_remain_jobs is not None:
                self.finished_store_req.add(req_id)

        return finished_sending

    def lookup(self, num_tokens: int, block_hashes: Sequence[BlockHash]) -> int:
        """Check how many prefix tokens exist in the store.

        Checks across all rank-specific key namespaces that may be loaded. A
        hit covering all ``num_tokens`` is re-derived below the request end so
        the last token is recomputed for sampling.
        """
        if self._capacity_only:
            return 0

        token_len = self.coord.align_lookup_length(num_tokens)
        if not block_hashes or token_len <= 0:
            return 0

        # Build per-(group, hash) candidate keys expanded across rank namespaces.
        # candidate_meta stores the (group, hash_bytes) for key slice.
        candidate_keys: list[str] = []
        candidate_meta: list[tuple[int, bytes]] = []
        fine_grained = self.coord.enable_partial_hash_hits
        lookup_masks = None if fine_grained else self.coord.lookup_mask(token_len)
        for g_idx, db in enumerate(self.token_dbs):
            spec_block_size = db.block_size
            key_prefixes = self._lookup_key_prefixes[g_idx]
            if fine_grained:
                max_units = min(len(block_hashes), token_len // self.hash_block_size)
                unit_ids: range | list[int] = range(max_units)
                group_hashes: Sequence[BlockHash] = block_hashes
            else:
                lookup_mask = lookup_masks[g_idx]  # type: ignore[index]
                group_hashes = self.coord.block_hashes_for_spec(
                    block_hashes, self._kv_cache_groups[g_idx].kv_cache_spec
                )
                max_chunks = min(len(group_hashes), cdiv(token_len, spec_block_size))
                mask_limit = (
                    max_chunks
                    if lookup_mask is None
                    else min(max_chunks, len(lookup_mask))
                )
                unit_ids = [
                    chunk_id
                    for chunk_id in range(mask_limit)
                    if lookup_mask is None or lookup_mask[chunk_id]
                ]
            for chunk_id in unit_ids:
                h = group_hashes[chunk_id]
                hash_hex = h.hex()
                for key_prefix in key_prefixes:
                    candidate_keys.append(
                        PoolKey.build_key_string(key_prefix, hash_hex)
                    )
                candidate_meta.append((g_idx, bytes(h)))

        if not candidate_keys:
            return 0

        lookup_start = time.perf_counter()
        try:
            res = self.store.batch_is_exist(candidate_keys)
            self._record_kv_connector_operation(
                "lookup_exists",
                time.perf_counter() - lookup_start,
                len(candidate_keys),
            )
        except Exception as e:
            self._record_kv_connector_operation(
                "lookup_exists",
                time.perf_counter() - lookup_start,
                len(candidate_keys),
                status="error",
                num_failed_keys=len(candidate_keys),
            )
            logger.error("Remote connection failed in lookup: %s", e)
            return 0

        # A (group, hash) is "present" only when every namespace that will be
        # loaded has it (per-group count: sharded groups need every rank's
        # shard, replicated groups one namespace per unique KV head).
        exists_set = set()
        pos = 0
        for g_idx, hash_bytes in candidate_meta:
            count = len(self._lookup_key_prefixes[g_idx])
            if all(res[pos + j] == 1 for j in range(count)):
                exists_set.add((g_idx, hash_bytes))
            pos += count

        cached_block_pool = ExternalCachedBlockPool(
            self.hash_block_size,
            exists_set,
        )
        _masks, hit_length = self.coord.find_longest_cache_hit(
            block_hashes,
            token_len,
            cached_block_pool,
        )
        if hit_length >= num_tokens:
            usable_length = self.coord.align_lookup_length(num_tokens - 1)
            if usable_length <= 0:
                return 0
            _masks, hit_length = self.coord.find_longest_cache_hit(
                block_hashes,
                usable_length,
                cached_block_pool,
            )
        return hit_length

    def get_kv_events(self) -> list[BlockStored]:
        if self.enable_kv_events and self.kv_send_thread is not None:
            return self.kv_send_thread.get_kv_events()
        return []

    def close(self) -> None:
        """Release the MooncakeDistributedStore handle on teardown.

        Closing the store frees its TransferEngine, the registered RDMA
        buffers, and the connection to the master server. Idempotent so it is
        safe to call from both the explicit shutdown path and ``__del__``.
        """
        store = getattr(self, "store", None)
        if store is None:
            return
        self.store = None
        try:
            store.close()
        except Exception as e:
            logger.warning("Error closing MooncakeDistributedStore: %s", e)

_compute_group_tp_replication_factors()

Return the number of byte-identical TP replicas per cache group.

DCP and Mamba use 1; MLA uses tp_size; GQA uses tp_size // num_kv_head.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
def _compute_group_tp_replication_factors(self) -> tuple[int, ...]:
    """Return the number of byte-identical TP replicas per cache group.

    DCP and Mamba use 1; MLA uses ``tp_size``; GQA uses
    ``tp_size // num_kv_head``.
    """
    return tuple(
        self._spec_tp_replication_factor(group.kv_cache_spec)
        for group in self._kv_cache_groups
    )

close()

Release the MooncakeDistributedStore handle on teardown.

Closing the store frees its TransferEngine, the registered RDMA buffers, and the connection to the master server. Idempotent so it is safe to call from both the explicit shutdown path and __del__.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
def close(self) -> None:
    """Release the MooncakeDistributedStore handle on teardown.

    Closing the store frees its TransferEngine, the registered RDMA
    buffers, and the connection to the master server. Idempotent so it is
    safe to call from both the explicit shutdown path and ``__del__``.
    """
    store = getattr(self, "store", None)
    if store is None:
        return
    self.store = None
    try:
        store.close()
    except Exception as e:
        logger.warning("Error closing MooncakeDistributedStore: %s", e)

get_finished(finished_req_ids, meta)

Issue all I/O and get completed send/recv request IDs.

All load and store I/O requests are issued here (after model compute is launched on the compute stream) for better compute-I/O overlap.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
def get_finished(
    self,
    finished_req_ids: set[str],
    meta: MooncakeStoreConnectorMetadata,
) -> tuple[set[str], set[str]]:
    """Issue all I/O and get completed send/recv request IDs.

    All load and store I/O requests are issued here (after model
    compute is launched on the compute stream) for better
    compute-I/O overlap.
    """
    if self._capacity_only:
        return set(), set()

    # Issue async loads
    for request in meta.requests:
        load_spec = request.load_spec
        if load_spec is None or not load_spec.can_load:
            continue

        load_spec.token_len = load_spec.kvpool_cached_tokens
        self.recv_request_queue.put(request)

    assert self.load_async, "load_async must be True for better performance."
    # Issue stores with CUDA event synchronization.
    if self.kv_role in ["kv_producer", "kv_both"]:
        current_event = None
        for request in meta.requests:
            if request.can_save:
                current_event = torch.cuda.Event()
                current_event.record()
                break

        for request in meta.requests:
            if not request.can_save:
                continue
            request.current_event = current_event
            assert self.kv_send_thread is not None
            self.kv_send_thread.add_stored_request(request.req_id)
            self.kv_send_thread.add_request(request)

    # Check completion of previously queued transfers
    done_sending = (
        self._get_and_clear_finished_sending(finished_req_ids, meta)
        if self.kv_role in ["kv_producer", "kv_both"]
        else set()
    )

    done_recving: set[str] = set()
    if self.load_async:
        for recv_thread in self.kv_recv_threads:
            done_recving |= recv_thread.get_and_clear_finished_requests()

    logger.debug(
        "Completed send: %d, recv: %d, tp_rank: %d",
        len(done_sending),
        len(done_recving),
        self.tp_rank,
    )
    return done_sending, done_recving

lookup(num_tokens, block_hashes)

Check how many prefix tokens exist in the store.

Checks across all rank-specific key namespaces that may be loaded. A hit covering all num_tokens is re-derived below the request end so the last token is recomputed for sampling.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
def lookup(self, num_tokens: int, block_hashes: Sequence[BlockHash]) -> int:
    """Check how many prefix tokens exist in the store.

    Checks across all rank-specific key namespaces that may be loaded. A
    hit covering all ``num_tokens`` is re-derived below the request end so
    the last token is recomputed for sampling.
    """
    if self._capacity_only:
        return 0

    token_len = self.coord.align_lookup_length(num_tokens)
    if not block_hashes or token_len <= 0:
        return 0

    # Build per-(group, hash) candidate keys expanded across rank namespaces.
    # candidate_meta stores the (group, hash_bytes) for key slice.
    candidate_keys: list[str] = []
    candidate_meta: list[tuple[int, bytes]] = []
    fine_grained = self.coord.enable_partial_hash_hits
    lookup_masks = None if fine_grained else self.coord.lookup_mask(token_len)
    for g_idx, db in enumerate(self.token_dbs):
        spec_block_size = db.block_size
        key_prefixes = self._lookup_key_prefixes[g_idx]
        if fine_grained:
            max_units = min(len(block_hashes), token_len // self.hash_block_size)
            unit_ids: range | list[int] = range(max_units)
            group_hashes: Sequence[BlockHash] = block_hashes
        else:
            lookup_mask = lookup_masks[g_idx]  # type: ignore[index]
            group_hashes = self.coord.block_hashes_for_spec(
                block_hashes, self._kv_cache_groups[g_idx].kv_cache_spec
            )
            max_chunks = min(len(group_hashes), cdiv(token_len, spec_block_size))
            mask_limit = (
                max_chunks
                if lookup_mask is None
                else min(max_chunks, len(lookup_mask))
            )
            unit_ids = [
                chunk_id
                for chunk_id in range(mask_limit)
                if lookup_mask is None or lookup_mask[chunk_id]
            ]
        for chunk_id in unit_ids:
            h = group_hashes[chunk_id]
            hash_hex = h.hex()
            for key_prefix in key_prefixes:
                candidate_keys.append(
                    PoolKey.build_key_string(key_prefix, hash_hex)
                )
            candidate_meta.append((g_idx, bytes(h)))

    if not candidate_keys:
        return 0

    lookup_start = time.perf_counter()
    try:
        res = self.store.batch_is_exist(candidate_keys)
        self._record_kv_connector_operation(
            "lookup_exists",
            time.perf_counter() - lookup_start,
            len(candidate_keys),
        )
    except Exception as e:
        self._record_kv_connector_operation(
            "lookup_exists",
            time.perf_counter() - lookup_start,
            len(candidate_keys),
            status="error",
            num_failed_keys=len(candidate_keys),
        )
        logger.error("Remote connection failed in lookup: %s", e)
        return 0

    # A (group, hash) is "present" only when every namespace that will be
    # loaded has it (per-group count: sharded groups need every rank's
    # shard, replicated groups one namespace per unique KV head).
    exists_set = set()
    pos = 0
    for g_idx, hash_bytes in candidate_meta:
        count = len(self._lookup_key_prefixes[g_idx])
        if all(res[pos + j] == 1 for j in range(count)):
            exists_set.add((g_idx, hash_bytes))
        pos += count

    cached_block_pool = ExternalCachedBlockPool(
        self.hash_block_size,
        exists_set,
    )
    _masks, hit_length = self.coord.find_longest_cache_hit(
        block_hashes,
        token_len,
        cached_block_pool,
    )
    if hit_length >= num_tokens:
        usable_length = self.coord.align_lookup_length(num_tokens - 1)
        if usable_length <= 0:
            return 0
        _masks, hit_length = self.coord.find_longest_cache_hit(
            block_hashes,
            usable_length,
            cached_block_pool,
        )
    return hit_length

register_cross_layers_kv_caches(kv_cache)

Register a cross-layers KV cache tensor.

Wraps the unified tensor in a single-entry dict so that the existing stride-based logic in register_kv_caches() produces the correct single-segment result (block_len = page_size * num_layers).

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
def register_cross_layers_kv_caches(self, kv_cache: torch.Tensor) -> None:
    """Register a cross-layers KV cache tensor.

    Wraps the unified tensor in a single-entry dict so that the
    existing stride-based logic in register_kv_caches() produces
    the correct single-segment result (block_len = page_size * num_layers).
    """
    self.register_kv_caches({"__cross_layer__": kv_cache})

register_kv_caches(kv_caches)

Register KV cache tensors and start transfer threads.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
def register_kv_caches(
    self,
    kv_caches: dict[str, torch.Tensor | list[torch.Tensor]],
) -> None:
    """Register KV cache tensors and start transfer threads."""
    if self._capacity_only:
        return
    if not kv_caches:
        logger.warning("No KV caches to offload.")
        return

    # Resolve each entry to a representative tensor for storage
    # deduplication. For attention layers the value is already a tensor;
    # for Mamba layers it is a list of tensors that all share the same
    # underlying raw storage, so we take the first one.
    def _repr_tensor(v: torch.Tensor | list[torch.Tensor]) -> torch.Tensor:
        assert isinstance(v, torch.Tensor | list)
        return v if isinstance(v, torch.Tensor) else v[0]

    assert self.cache_config.num_gpu_blocks is not None
    self.num_blocks = self.cache_config.num_gpu_blocks

    seen_ptrs: set[int] = set()
    addrs: list[int] = []
    block_lens: list[int] = []

    for value in kv_caches.values():
        cache = _repr_tensor(value)
        cache_storage = cache.untyped_storage()
        base_addr = cache_storage.data_ptr()
        if base_addr in seen_ptrs:
            continue
        seen_ptrs.add(base_addr)
        region_len = cache_storage.nbytes()

        ret = self.store.register_buffer(base_addr, region_len)
        if ret != 0:
            logger.error(
                "register_buffer failed for addr %#x len %d: %d",
                base_addr,
                region_len,
                ret,
            )

        # Detect layout via stride: a dim whose byte-stride exceeds
        # page_size_bytes is an outer segment dim (e.g. the K/V dim of
        # FlashAttn's (2, num_blocks, ...)). FlashInfer/MLA's blocks-
        # outermost layout has no such dim and yields a single segment.
        el = cache.element_size()
        page_size_bytes = region_len // self.num_blocks
        outer_dims = [
            d for d in range(cache.ndim) if cache.stride(d) * el > page_size_bytes
        ]
        if not outer_dims:
            # Blocks-first layout (FlashInfer / MLA): one segment.
            addrs.append(base_addr)
            block_lens.append(page_size_bytes)
        else:
            # K/V-first layout (FlashAttn / ROCm): split segments.
            seg_stride = cache.stride(outer_dims[0]) * el
            for idx in range(cache.shape[outer_dims[0]]):
                addrs.append(base_addr + idx * seg_stride)
                block_lens.append(seg_stride // self.num_blocks)

    logger.info(
        "Registered KV caches: num_groups=%d, num_segments=%d, num_blocks=%d",
        len(self.token_dbs),
        len(addrs),
        self.num_blocks,
    )

    for db in self.token_dbs:
        db.set_kv_caches_base_addr(addrs)
        db.set_block_len(block_lens)

    # Start transfer threads
    if self.kv_role in ["kv_producer", "kv_both"]:
        ready_event_sending = threading.Event()
        self.kv_send_thread = KVCacheStoreSendingThread(
            self.store,
            self.coord,
            self.token_dbs,
            self.block_size,
            self.tp_rank,
            self._group_tp_replication_factors,
            self.kv_role,
            ready_event_sending,
            self.enable_kv_events,
            self.store_replicate_config,
            enable_group_semantics=self.enable_group_semantics,
            supports_group_ids=self._supports_group_ids,
            record_operation=self._record_kv_connector_operation,
        )
        self.kv_send_thread.start()

    self.kv_recv_threads = []
    ready_events_recving = []
    for i in range(self.num_recv_threads):
        ready_event_recving = threading.Event()
        recv_thread = KVCacheStoreRecvingThread(
            self.store,
            self.coord,
            self.token_dbs,
            self.block_size,
            self.tp_rank,
            ready_event_recving,
            disk_offload_buffer_budget_bytes=self.disk_offload_buffer_budget_bytes,
            record_operation=self._record_kv_connector_operation,
            request_queue=self.recv_request_queue,
        )
        recv_thread.name = f"KVCacheStoreRecvingThread-{i}"
        recv_thread.start()
        self.kv_recv_threads.append(recv_thread)
        ready_events_recving.append(ready_event_recving)
    for ready_event_recving in ready_events_recving:
        ready_event_recving.wait()
    logger.info(
        "Started %d Mooncake KV-load receive thread(s)", self.num_recv_threads
    )

start_load_kv(metadata)

No-op: loads are issued in get_finished() for overlap.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
def start_load_kv(
    self,
    metadata: MooncakeStoreConnectorMetadata,
):
    """No-op: loads are issued in get_finished() for overlap."""
    pass

wait_for_save(metadata)

No-op: stores are issued in get_finished() for overlap.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
def wait_for_save(
    self,
    metadata: MooncakeStoreConnectorMetadata,
):
    """No-op: stores are issued in get_finished() for overlap."""
    pass

_parse_size(value)

Parse storage size strings with units: GB, MB, KB, B.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
def _parse_size(value: Any) -> int:
    """Parse storage size strings with units: GB, MB, KB, B."""
    if isinstance(value, int):
        return value
    if not isinstance(value, str):
        try:
            return int(value)
        except (TypeError, ValueError) as e:
            raise TypeError(f"Unsupported type for size: {type(value)}") from e

    cleaned = value.strip().lower()
    if not cleaned:
        raise ValueError("Size cannot be empty.")

    unit_multipliers = {
        "gb": 1024**3,
        "mb": 1024**2,
        "kb": 1024,
        "b": 1,
    }
    match = re.match(r"^\s*([\d.]+)\s*(gb|mb|kb|b)?\s*$", cleaned)
    if not match:
        raise ValueError(f"Invalid format: '{value}'")

    number_str = match.group(1)
    unit = match.group(2) or "b"
    multiplier = unit_multipliers[unit]

    try:
        numeric_value = float(number_str)
    except ValueError as exc:
        raise ValueError(f"Invalid numeric value '{number_str}' in: '{value}'") from exc
    return int(numeric_value * multiplier)

_split_disk_offload_load_batches(keys, addrs, sizes, usable_budget_bytes, raw_budget_bytes)

Split a GET into sub-batches that fit the owner's staging buffer.

addrs[i] / sizes[i] are scatter-gather lists (K/V or multi-layer segments) for key i. usable_budget_bytes caps a multi-key batch; raw_budget_bytes is the hard per-key cap.

Returns (batches, oversize_key). Aborts with ([], key) if any single key exceeds raw_budget_bytes; otherwise oversize_key is None.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
def _split_disk_offload_load_batches(
    keys: list[str],
    addrs: list[list[int]],
    sizes: list[list[int]],
    usable_budget_bytes: int,
    raw_budget_bytes: int,
) -> tuple[list[tuple[list[str], list[list[int]], list[list[int]]]], str | None]:
    """Split a GET into sub-batches that fit the owner's staging buffer.

    ``addrs[i]`` / ``sizes[i]`` are scatter-gather lists (K/V or multi-layer
    segments) for key ``i``. ``usable_budget_bytes`` caps a multi-key batch;
    ``raw_budget_bytes`` is the hard per-key cap.

    Returns ``(batches, oversize_key)``. Aborts with ``([], key)`` if any
    single key exceeds ``raw_budget_bytes``; otherwise ``oversize_key`` is
    ``None``.
    """
    batches: list[tuple[list[str], list[list[int]], list[list[int]]]] = []
    batch_keys: list[str] = []
    batch_addrs: list[list[int]] = []
    batch_sizes: list[list[int]] = []
    batch_bytes = 0

    for key, addr, size in zip(keys, addrs, sizes, strict=True):
        key_bytes = _estimate_disk_offload_staging_bytes(size)
        if key_bytes > raw_budget_bytes:
            return [], key
        if key_bytes > usable_budget_bytes:
            if batch_keys:
                batches.append((batch_keys, batch_addrs, batch_sizes))
                batch_keys, batch_addrs, batch_sizes = [], [], []
                batch_bytes = 0
            batches.append(([key], [addr], [size]))
            continue
        if batch_keys and batch_bytes + key_bytes > usable_budget_bytes:
            batches.append((batch_keys, batch_addrs, batch_sizes))
            batch_keys, batch_addrs, batch_sizes = [], [], []
            batch_bytes = 0
        batch_keys.append(key)
        batch_addrs.append(addr)
        batch_sizes.append(size)
        batch_bytes += key_bytes

    if batch_keys:
        batches.append((batch_keys, batch_addrs, batch_sizes))
    return batches, None

get_zmq_rpc_path_lookup(vllm_config)

Construct IPC path for ZMQ lookup socket.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
def get_zmq_rpc_path_lookup(vllm_config: VllmConfig) -> str:
    """Construct IPC path for ZMQ lookup socket."""
    assert vllm_config.kv_transfer_config is not None
    dp_rank = vllm_config.parallel_config.data_parallel_index
    base_url = envs.VLLM_RPC_BASE_PATH
    rpc_port = 0
    hostname = socket.gethostname()
    extra_config = vllm_config.kv_transfer_config.kv_connector_extra_config
    if "lookup_rpc_port" in extra_config:
        rpc_port = extra_config["lookup_rpc_port"]
    logger.debug("Base URL: %s, RPC Port: %s", base_url, rpc_port)
    return (
        f"ipc://{base_url}/lookup_rpc_port_{rpc_port}_host_{hostname}_dp_rank{dp_rank}"
    )