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,
        group_participates: Sequence[bool] | None = None,
        is_hma_required: bool = False,
    ):
        super().__init__(
            store,
            token_databases,
            block_size,
            tp_rank,
            ready_event,
            name="KVCacheStoreRecvingThread",
            record_operation=record_operation,
            request_queue=request_queue,
        )
        self.group_participates = (
            list(group_participates)
            if group_participates is not None
            else [True] * len(token_databases)
        )
        # _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()
        # With HMA the scheduler tracks a single merged group while block IDs
        # are only unique within a group, so failures are reported per request.
        self._is_hma_required = is_hma_required
        self._failed_requests: set[str] = 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 set_failed_request(self, req_id: str):
        with self.done_task_lock:
            self._failed_requests.add(req_id)

    def get_and_clear_failed_requests(self) -> set[str]:
        with self.done_task_lock:
            failed = self._failed_requests.copy()
            self._failed_requests.clear()
        return failed

    def _report_load_error(self, req_id: str, block_ids: list[int]) -> None:
        if self._is_hma_required:
            self.set_failed_request(req_id)
        else:
            self._add_load_error_block_ids(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)
        tail_key_boundaries = {
            boundary.group_id: boundary.num_tokens
            for boundary in (
                req_meta.load_spec.tail_key_boundaries  # type: ignore[union-attr]
            )
        }

        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):
            if not self.group_participates[g_idx]:
                continue
            mask = load_mask_per_group[g_idx]
            chunks: list[tuple[int, int]] = []
            store_shard_ids: list[StoreShardId] = []
            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
                boundary_tokens = (
                    tail_key_boundaries.get(g_idx) if end == token_len else None
                )
                if boundary_tokens is not None:
                    block_hash = req_meta.block_hashes[
                        boundary_tokens // db.hash_block_size - 1
                    ]
                for store_shard_id in db.store_layout.local_shard_ids:
                    key_list.append(db.store_layout.key_for(store_shard_id, block_hash))
                    chunks.append((start, end))
                    store_shard_ids.append(store_shard_id)
            g_addrs, g_sizes, g_block_ids = db.store_layout.prepare_values(
                chunks,
                req_meta.block_ids[g_idx],
                store_shard_ids,
            )
            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._report_load_error(req_id, 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._report_load_error(
                        req_id, [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._report_load_error(req_id, 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.

Methods:

  • finish_store_job –

    Retire a job from the ledger and report its blocks as no longer read.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 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
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
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,
        group_participates: Sequence[bool] | 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.group_participates = (
            list(group_participates)
            if group_participates is not None
            else [True] * len(token_databases)
        )
        # req_id -> ids of its store jobs that are still queued or running.
        # Keying by store_job_id, which never repeats for the engine's lifetime,
        # rather than counting jobs per request id makes the ledger immune to id
        # reuse across preemption: a job left over from a retired generation is
        # missing from the set its resumed generation builds, so it can no longer
        # retire that generation, rewind its resume offset, or mark it skipped.
        self.stored_requests: dict[str, set[int]] = {}
        # store_job_id -> times this rank finished with it, drained every step
        # so the scheduler can release the blocks it referenced for those jobs.
        self._completed_saves: dict[int, 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] = {}
        # Retained only after a failed store so retry events can recover the
        # token suffix without full snapshots on the normal path.
        self._retry_token_ids: dict[str, tuple[int, list[int]]] = {}

    def add_request(self, request: ReqMeta) -> None:
        # Register before enqueueing so a job is never picked up unledgered.
        assert request.store_job_id is not None
        with self.done_task_lock:
            self.stored_requests.setdefault(request.req_id, set()).add(
                request.store_job_id
            )
        super().add_request(request)

    def is_live_store_job(self, req_meta: ReqMeta) -> bool:
        with self.done_task_lock:
            return req_meta.store_job_id in self.stored_requests.get(
                req_meta.req_id, ()
            )

    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)
            self._retry_token_ids.pop(req_id, None)

    def finish_store_job(self, req_meta: ReqMeta) -> None:
        """Retire a job from the ledger and report its blocks as no longer read.

        Every path out of a job must reach this, skips and failures included: a
        job that never reports leaves its blocks referenced for the rest of the
        run. The discard is a no-op for a job whose generation already retired.
        """
        store_job_id = req_meta.store_job_id
        assert store_job_id is not None, (
            "a queued store job always carries a store_job_id"
        )
        with self.done_task_lock:
            live = self.stored_requests.get(req_meta.req_id)
            if live is not None:
                live.discard(store_job_id)
            self._completed_saves[store_job_id] = (
                self._completed_saves.get(store_job_id, 0) + 1
            )

    def take_completed_saves(self) -> dict[int, int]:
        with self.done_task_lock:
            completed = self._completed_saves
            self._completed_saves = {}
        return completed

    def _record_saved(self, req_meta: ReqMeta, token_len: int) -> None:
        # Guard on job liveness so neither a concurrent finish/preempt pop nor a
        # stale job's offset is written back over the live generation's.
        with self.done_task_lock:
            if req_meta.store_job_id in self.stored_requests.get(req_meta.req_id, ()):
                self._saved_offset[req_meta.req_id] = token_len

    def _get_retry_token_ids(self, req_meta: ReqMeta) -> tuple[int, list[int]] | None:
        """Return retry state only if this store job is still live."""
        with self.done_task_lock:
            if req_meta.store_job_id not in self.stored_requests.get(
                req_meta.req_id, ()
            ):
                return None
            return self._retry_token_ids.get(req_meta.req_id)

    def _update_retry_token_ids(
        self,
        req_meta: ReqMeta,
        save_completed: bool,
        token_ids_start: int,
        event_token_ids: list[int] | None,
    ) -> None:
        """Update retry state without letting a stale job touch a reused ID."""
        with self.done_task_lock:
            if req_meta.store_job_id not in self.stored_requests.get(
                req_meta.req_id, ()
            ):
                return
            if save_completed:
                self._retry_token_ids.pop(req_meta.req_id, None)
            elif event_token_ids is not None:
                self._retry_token_ids[req_meta.req_id] = (
                    token_ids_start,
                    event_token_ids,
                )

    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_meta: ReqMeta) -> bool:
        req_id = req_meta.req_id
        with self.done_task_lock:
            already_skipped = req_id in self._skip_store_requests
            self._store_pressure_active = True
            # The pressure itself is global, but only a live job may sentence its
            # own request to being skipped.
            if req_meta.store_job_id in self.stored_requests.get(req_id, ()):
                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 _boundary_puts(
        self, req_meta: ReqMeta
    ) -> list[tuple[str, list[int], list[int], KeyMetadata]]:
        """Puts for ``req_meta.boundary_puts``: each block under the hash of
        the prefix ending at its ``num_tokens``.

        The scheduler resolves and pins every block, so none is looked up
        positionally here. That matters for mamba "align" states: ``store_mask``
        masks mamba groups out of the normal save, which resolves a chunk's
        address as ``req_meta.block_ids[g][start // block_size]``. An align-mode
        table is mutated in place (a superseded state block is freed and
        nulled; speculative blocks relocate) without telling the connector, so
        a retried positional read could hit a block that now belongs to another
        request. The handed-off block *is* the state.
        """
        hash_block_size = self.coord.hash_block_size
        puts: list[tuple[str, list[int], list[int], KeyMetadata]] = []
        for group_id, block_id, num_tokens in req_meta.boundary_puts or []:
            if (
                not self.group_participates[group_id]
                or num_tokens == 0
                or block_id == NULL_BLOCK_ID
            ):
                continue
            # A negative index would silently key the block by the last hash.
            assert num_tokens % hash_block_size == 0, (
                f"Boundary put at {num_tokens} tokens is not a multiple of the "
                f"hash block size {hash_block_size}"
            )
            hash_idx = num_tokens // hash_block_size - 1
            if hash_idx >= len(req_meta.block_hashes):
                continue
            db = self.token_databases[group_id]
            # Distribute across ranks by the same rule as normal chunks.
            put_step = self.group_put_steps[group_id]
            put_step_rank = (self.tp_rank + group_id) % put_step
            if (cdiv(num_tokens, db.block_size) - 1) % put_step != put_step_rank:
                continue
            addr, size = db.prepare_value_for_block(block_id)
            puts.append(
                (db.key_for(req_meta.block_hashes[hash_idx]), addr, size, db.metadata)
            )
        return puts

    def _maybe_offload_boundary_states(self, req_meta: ReqMeta) -> bool:
        """Persist this job's boundary puts, deduped against the store.

        These are every mamba key the connector writes (``store_mask`` excludes
        mamba groups from the positional normal save) plus the other groups'
        partial-tail blocks in the normal save's lcm gap.

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

        """
        if not req_meta.boundary_puts or not req_meta.block_hashes:
            return True
        puts = self._boundary_puts(req_meta)

        if not puts:
            return True
        keys = [key for key, _, _, _ in puts]
        addrs = [addr for _, addr, _, _ in puts]
        sizes = [size for _, _, size, _ in puts]
        group_ids: list[str] | None = (
            [
                _make_mooncake_group_id(metadata, key.rsplit("@", 1)[-1])
                for key, _, _, metadata in puts
            ]
            if self.enable_group_semantics and self.supports_group_ids
            else None
        )
        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 boundary-state 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 boundary-state 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(
                "Boundary-state 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)
            return False

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

    def _handle_request(self, req_meta: ReqMeta):
        # The single `finally` is the only way out, so the scheduler releases
        # this job's GPU block references however the job ends.
        save_completed = False
        token_len = 0
        req_id = req_meta.req_id
        event_token_ids = req_meta.token_ids
        token_ids_start = req_meta.token_ids_start
        try:
            # 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
            current_event = req_meta.current_event

            if not self.is_live_store_job(req_meta):
                return

            if self.enable_kv_event:
                retry_token_ids = self._get_retry_token_ids(req_meta)
                if retry_token_ids is not None and event_token_ids is not None:
                    retry_start, retry_ids = retry_token_ids
                    if retry_start + len(retry_ids) == token_ids_start:
                        event_token_ids = retry_ids + event_token_ids
                        token_ids_start = retry_start

            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 handed-off mamba boundary states (independent of the
            # normal positional save, which may be skipped this step).
            if not self._maybe_offload_boundary_states(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.prefill_end_tokens,
            )

            starts: list[int] = []
            ends: list[int] = []
            keys: list[str] = []
            event_specs: list[tuple[int, int, int, BlockHash]] | None = (
                [] if self.enable_kv_event else None
            )
            group_indices: list[int] = []
            store_shard_ids: list[StoreShardId] = []
            for g_idx, db in enumerate(self.token_databases):
                if not self.group_participates[g_idx]:
                    continue
                # 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
                group_blocks = block_ids_per_group[g_idx]
                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,
                ):
                    block_idx = start // db.block_size
                    group_blocks = block_ids_per_group[g_idx]
                    if block_idx >= len(group_blocks) or (
                        group_blocks[block_idx] == NULL_BLOCK_ID
                    ):
                        logger.debug(
                            "Skipping unavailable Mooncake store source block "
                            "(req=%s, group=%d, block=%d)",
                            req_id,
                            g_idx,
                            block_idx,
                        )
                        continue
                    for store_shard_id in db.store_layout.local_shard_ids:
                        starts.append(start)
                        ends.append(end)
                        keys.append(db.store_layout.key_for(store_shard_id, block_hash))
                        group_indices.append(g_idx)
                        store_shard_ids.append(store_shard_id)
                        if event_specs is not None:
                            event_specs.append((start, end, g_idx, block_hash))

            if not keys:
                self._record_saved(req_meta, token_len)
                save_completed = True
                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_meta, token_len)
                save_completed = True
                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 event_specs is not None:
                    event_specs = [event_specs[i] for i in missing_indices]
                group_indices = [group_indices[i] for i in missing_indices]
                store_shard_ids = [store_shard_ids[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]] = []
            chunks_per_group: list[list[tuple[int, int]]] = [
                [] for _ in self.token_databases
            ]
            shards_per_group: list[list[StoreShardId]] = [
                [] for _ in self.token_databases
            ]
            for start, end, g_idx, store_shard_id in zip(
                starts,
                ends,
                group_indices,
                store_shard_ids,
                strict=True,
            ):
                chunks_per_group[g_idx].append((start, end))
                shards_per_group[g_idx].append(store_shard_id)
            for g_idx, chunks in enumerate(chunks_per_group):
                if not chunks:
                    continue
                db = self.token_databases[g_idx]
                group_addrs, group_sizes, _ = db.store_layout.prepare_values(
                    chunks,
                    block_ids_per_group[g_idx],
                    shards_per_group[g_idx],
                )
                addrs.extend(group_addrs)
                sizes.extend(group_sizes)

            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

            failed_indices: set[int] = set()
            put_had_exception = False
            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 key %s, error: %s", keys, e)
                put_had_exception = True
            else:
                failed_indices = {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_indices else "ok",
                    num_failed_keys=len(failed_indices),
                )
                failed_codes = {res[i] for i in failed_indices}
                if failed_indices:
                    logger.warning(
                        "batch_put failed: %d/%d keys failed "
                        "(codes=%s, batch_bytes=%d), first_key=%s",
                        len(failed_indices),
                        len(keys),
                        failed_codes,
                        batch_bytes,
                        keys[0],
                    )
                if (
                    MOONCAKE_NO_AVAILABLE_HANDLE in failed_codes
                    and not self._mark_request_skipped_for_pressure(req_meta)
                ):
                    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,
                    )

            if not put_had_exception and not failed_indices:
                self._record_saved(req_meta, token_len)
                save_completed = True
                if self._clear_store_pressure():
                    logger.info(
                        "Mooncake CPU/disk offloading pressure cleared "
                        "after a successful store batch"
                    )

            stored_events: list[BlockStored] = []
            if self.enable_kv_event and not put_had_exception:
                assert event_specs is not None
                # BlockStored is a logical-block event, while one block may map
                # to several Store shards. Emit once only after every missing
                # shard for that block succeeded. Shards that already existed
                # were removed before this mapping and are already satisfied.
                indices_by_event: dict[tuple[int, int, int, BlockHash], list[int]] = {}
                for index, event_spec in enumerate(event_specs):
                    indices_by_event.setdefault(event_spec, []).append(index)

                token_ids_end = token_ids_start + len(event_token_ids or ())
                for (
                    s,
                    end,
                    g_idx,
                    block_hash,
                ), event_indices in indices_by_event.items():
                    if any(index in failed_indices for index in event_indices):
                        continue
                    db = self.token_databases[g_idx]
                    token_ids = (
                        event_token_ids[s - token_ids_start : end - token_ids_start]
                        if event_token_ids is not None
                        and token_ids_start <= s
                        and end <= token_ids_end
                        else []
                    )
                    stored_events.append(
                        BlockStored(
                            block_hashes=[maybe_convert_block_hash(block_hash)],
                            # Store filtering can separate adjacent request
                            # blocks, so derive the predecessor from the request.
                            parent_block_hash=(
                                maybe_convert_block_hash(
                                    req_meta.block_hashes[s // db.hash_block_size - 1]
                                )
                                if s > 0
                                else None
                            ),
                            token_ids=token_ids,
                            block_size=db.block_size,
                            lora_id=None,
                            medium="cpu",
                            lora_name=None,
                            group_idx=g_idx,
                        )
                    )

            if self.enable_kv_event and stored_events:
                self.update_kv_event(stored_events)
        finally:
            if self.enable_kv_event and token_len:
                self._update_retry_token_ids(
                    req_meta,
                    save_completed,
                    token_ids_start,
                    event_token_ids,
                )
            self.finish_store_job(req_meta)
            self.request_queue.task_done()

_boundary_puts(req_meta)

Puts for req_meta.boundary_puts: each block under the hash of the prefix ending at its num_tokens.

The scheduler resolves and pins every block, so none is looked up positionally here. That matters for mamba "align" states: store_mask masks mamba groups out of the normal save, which resolves a chunk's address as req_meta.block_ids[g][start // block_size]. An align-mode table is mutated in place (a superseded state block is freed and nulled; speculative blocks relocate) without telling the connector, so a retried positional read could hit a block that now belongs to another request. The handed-off block is the state.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
def _boundary_puts(
    self, req_meta: ReqMeta
) -> list[tuple[str, list[int], list[int], KeyMetadata]]:
    """Puts for ``req_meta.boundary_puts``: each block under the hash of
    the prefix ending at its ``num_tokens``.

    The scheduler resolves and pins every block, so none is looked up
    positionally here. That matters for mamba "align" states: ``store_mask``
    masks mamba groups out of the normal save, which resolves a chunk's
    address as ``req_meta.block_ids[g][start // block_size]``. An align-mode
    table is mutated in place (a superseded state block is freed and
    nulled; speculative blocks relocate) without telling the connector, so
    a retried positional read could hit a block that now belongs to another
    request. The handed-off block *is* the state.
    """
    hash_block_size = self.coord.hash_block_size
    puts: list[tuple[str, list[int], list[int], KeyMetadata]] = []
    for group_id, block_id, num_tokens in req_meta.boundary_puts or []:
        if (
            not self.group_participates[group_id]
            or num_tokens == 0
            or block_id == NULL_BLOCK_ID
        ):
            continue
        # A negative index would silently key the block by the last hash.
        assert num_tokens % hash_block_size == 0, (
            f"Boundary put at {num_tokens} tokens is not a multiple of the "
            f"hash block size {hash_block_size}"
        )
        hash_idx = num_tokens // hash_block_size - 1
        if hash_idx >= len(req_meta.block_hashes):
            continue
        db = self.token_databases[group_id]
        # Distribute across ranks by the same rule as normal chunks.
        put_step = self.group_put_steps[group_id]
        put_step_rank = (self.tp_rank + group_id) % put_step
        if (cdiv(num_tokens, db.block_size) - 1) % put_step != put_step_rank:
            continue
        addr, size = db.prepare_value_for_block(block_id)
        puts.append(
            (db.key_for(req_meta.block_hashes[hash_idx]), addr, size, db.metadata)
        )
    return puts

_get_retry_token_ids(req_meta)

Return retry state only if this store job is still live.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
def _get_retry_token_ids(self, req_meta: ReqMeta) -> tuple[int, list[int]] | None:
    """Return retry state only if this store job is still live."""
    with self.done_task_lock:
        if req_meta.store_job_id not in self.stored_requests.get(
            req_meta.req_id, ()
        ):
            return None
        return self._retry_token_ids.get(req_meta.req_id)

_maybe_offload_boundary_states(req_meta)

Persist this job's boundary puts, deduped against the store.

These are every mamba key the connector writes (store_mask excludes mamba groups from the positional normal save) plus the other groups' partial-tail blocks in the normal save's lcm gap.

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_boundary_states(self, req_meta: ReqMeta) -> bool:
    """Persist this job's boundary puts, deduped against the store.

    These are every mamba key the connector writes (``store_mask`` excludes
    mamba groups from the positional normal save) plus the other groups'
    partial-tail blocks in the normal save's lcm gap.

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

    """
    if not req_meta.boundary_puts or not req_meta.block_hashes:
        return True
    puts = self._boundary_puts(req_meta)

    if not puts:
        return True
    keys = [key for key, _, _, _ in puts]
    addrs = [addr for _, addr, _, _ in puts]
    sizes = [size for _, _, size, _ in puts]
    group_ids: list[str] | None = (
        [
            _make_mooncake_group_id(metadata, key.rsplit("@", 1)[-1])
            for key, _, _, metadata in puts
        ]
        if self.enable_group_semantics and self.supports_group_ids
        else None
    )
    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 boundary-state 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 boundary-state 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(
            "Boundary-state 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)
        return False

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

_update_retry_token_ids(req_meta, save_completed, token_ids_start, event_token_ids)

Update retry state without letting a stale job touch a reused ID.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
def _update_retry_token_ids(
    self,
    req_meta: ReqMeta,
    save_completed: bool,
    token_ids_start: int,
    event_token_ids: list[int] | None,
) -> None:
    """Update retry state without letting a stale job touch a reused ID."""
    with self.done_task_lock:
        if req_meta.store_job_id not in self.stored_requests.get(
            req_meta.req_id, ()
        ):
            return
        if save_completed:
            self._retry_token_ids.pop(req_meta.req_id, None)
        elif event_token_ids is not None:
            self._retry_token_ids[req_meta.req_id] = (
                token_ids_start,
                event_token_ids,
            )

finish_store_job(req_meta)

Retire a job from the ledger and report its blocks as no longer read.

Every path out of a job must reach this, skips and failures included: a job that never reports leaves its blocks referenced for the rest of the run. The discard is a no-op for a job whose generation already retired.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
def finish_store_job(self, req_meta: ReqMeta) -> None:
    """Retire a job from the ledger and report its blocks as no longer read.

    Every path out of a job must reach this, skips and failures included: a
    job that never reports leaves its blocks referenced for the rest of the
    run. The discard is a no-op for a job whose generation already retired.
    """
    store_job_id = req_meta.store_job_id
    assert store_job_id is not None, (
        "a queued store job always carries a store_job_id"
    )
    with self.done_task_lock:
        live = self.stored_requests.get(req_meta.req_id)
        if live is not None:
            live.discard(store_job_id)
        self._completed_saves[store_job_id] = (
            self._completed_saves.get(store_job_id, 0) + 1
        )

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[MooncakeLookupResult]] = {}

    def _lookup(
        self, num_tokens: int, block_hashes: list[BlockHash]
    ) -> MooncakeLookupResult:
        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 decode_lookup_response(resp)

    def lookup(
        self,
        req_id: str,
        num_tokens: int,
        block_hashes: list[BlockHash],
        non_block: bool = False,
    ) -> MooncakeLookupResult | 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 MooncakeLookupResult(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,
) -> MooncakeLookupResult | 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 MooncakeLookupResult(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 its load plan. - 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 its load plan.
    - ``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(encode_lookup_response(result))

                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)

MooncakeStoreWorker

Worker-side component for MooncakeStoreConnector.

Methods:

  • close –

    Release the MooncakeDistributedStore handle on teardown.

  • get_finished –

    Get completed send/recv request IDs.

  • get_mem_pool_context –

    Return a context manager for the custom MemPool, or None if

  • get_transfer_results –

    Get completed sends/recvs plus requests whose remote KV load failed.

  • lookup –

    Check how many prefix tokens exist in the store.

  • register_kv_caches –

    Register KV cache tensors and start transfer threads.

  • start_load_kv –

    Issue async loads.

  • wait_for_save –

    Issue async stores with CUDA event synchronization.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
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
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
class MooncakeStoreWorker:
    """Worker-side component for MooncakeStoreConnector."""

    @staticmethod
    def _create_mem_pool(
        extra_config: dict[str, Any], model_config: ModelConfig
    ) -> torch.cuda.MemPool | None:
        pool_type = str(extra_config.get("custom_mem_pool") or "").upper()
        if not pool_type:
            return None
        if pool_type not in ("NVLINK", "BAREX"):
            raise ValueError(
                f"Unsupported custom_mem_pool={pool_type!r}, "
                "expected 'NVLINK' or 'BAREX'"
            )
        if model_config.enable_sleep_mode or model_config.enable_cumem_allocator:
            raise ValueError(
                "custom_mem_pool is incompatible with enable_sleep_mode "
                "or enable_cumem_allocator; CuMemAllocator cannot manage "
                "allocations from the custom pool."
            )
        try:
            if pool_type == "NVLINK":
                from mooncake.allocator import NVLinkAllocator as allocator_cls
            else:  # pool_type == "BAREX"
                from mooncake.allocator import BarexAllocator as allocator_cls
        except ImportError as e:
            raise ImportError(
                f"custom_mem_pool={pool_type!r} requires "
                "mooncake-transfer-engine>=0.3.8. Please upgrade Mooncake."
            ) from e

        device = torch.device("cuda", torch.accelerator.current_device_index())
        allocator = allocator_cls.get_allocator(device)
        mem_pool = torch.cuda.MemPool(allocator.allocator())
        logger.info("Using Mooncake custom memory pool: %s", pool_type)
        return mem_pool

    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
        kv_role = vllm_config.kv_transfer_config.kv_role
        assert kv_role is not None
        self.kv_role = kv_role
        extra_config = vllm_config.kv_transfer_config.kv_connector_extra_config
        self.can_put = self.kv_role in ("kv_producer", "kv_both") or (
            extra_config.get("save_decode_cache", False)
        )
        self.load_async = extra_config.get("load_async", True)
        # Mirrors MooncakeStoreConnector._capacity_only.
        self._capacity_only = (
            self.kv_role == "kv_consumer"
            and not extra_config.get("enable_lookup", True)
            and not self.can_put
        )
        self.cache_config = vllm_config.cache_config
        self._is_hma_required = len(kv_cache_config.kv_cache_groups) > 1
        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()
        # Validate and create the custom memory pool before initializing the
        # store so failures cannot leak a partially initialized store handle.
        self._mem_pool = self._create_mem_pool(extra_config, model_config)

        self.store = MooncakeDistributedStore()
        local_ip = get_ip()
        local_hostname = rdma_utils.get_requester_local_hostname(local_ip)
        setup_mooncake_store(self.store, store_config, local_hostname)

        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

        self.coord = MooncakeStoreCoordinator.from_kv_cache_config(
            kv_cache_config, vllm_config, self.block_size, self.hash_block_size
        )
        self._kv_cache_groups = self.coord.kv_cache_groups
        self.store_tp_size, store_namespace, store_layout_cls = (
            self._select_store_layout(extra_config)
        )
        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", ""
                )
            ),
            store_namespace=store_namespace,
        )
        self._group_tp_replication_factors: tuple[int, ...] = (
            self._compute_group_tp_replication_factors()
        )
        self.token_dbs = self._build_token_databases(metadata, store_layout_cls)
        self._init_lookup_key_prefixes()

    def _supports_tp_sharded_store_layout(
        self,
        layout_cls: type[TPShardedStoreLayout] | None,
        extra_config: dict[str, Any],
    ) -> bool:
        if (
            layout_cls is None
            or self.pcp_size != 1
            or self.dcp_size != 1
            or len(self._kv_cache_groups) != 1
        ):
            return False

        # Subclasses may use different sharding or cache-lifetime semantics.
        return (
            type(self._kv_cache_groups[0].kv_cache_spec) is FullAttentionSpec
            and str(extra_config.get("enable_cross_layers_blocks", "False")).lower()
            != "true"
        )

    def _select_store_layout(
        self, extra_config: dict[str, Any]
    ) -> tuple[int | None, str, type[TPShardedStoreLayout] | None]:
        """Select the opt-in TP layout and its Store namespace."""
        lcm_store_tp_enabled = extra_config.get("enable_store_tp_lcm") is True
        store_tp_requested = (
            lcm_store_tp_enabled or extra_config.get("store_tp_size") is not None
        )
        if not store_tp_requested:
            return None, "", None

        requested_store_tp_size = resolve_store_tp_size(extra_config)
        cache_layout = self.cache_config.get_resolved_kv_cache_layout()
        layout_cls: type[TPShardedStoreLayout] | None = {
            KVCacheLayout.LBHNC: LBHNCStoreLayout,
            KVCacheLayout.LBNHC: LBNHCStoreLayout,
        }.get(cache_layout)

        if (
            requested_store_tp_size is not None
            and requested_store_tp_size >= self.tp_size
            and requested_store_tp_size % self.tp_size == 0
            and self._supports_tp_sharded_store_layout(layout_cls, extra_config)
        ):
            assert layout_cls is not None
            if self.num_kv_head % requested_store_tp_size == 0:
                if layout_cls is LBNHCStoreLayout:
                    logger.warning_once(
                        "Mooncake Store TP sharding is using the LBNHC (NHC) "
                        "KV cache layout, which creates many transfer segments "
                        "and may significantly reduce PUT/GET performance. Use "
                        "LBHNC (HNC) when supported by the attention backend."
                    )
                return (
                    requested_store_tp_size,
                    layout_cls.shared_namespace(requested_store_tp_size, self.pp_size),
                    layout_cls,
                )
            if self.num_kv_head == 1:
                logger.info(
                    "Mooncake heterogeneous-TP store sharing uses the replicated "
                    "MQA layout for store_tp_size=%d",
                    requested_store_tp_size,
                )
                return (
                    None,
                    f"@store_pp:{self.pp_size}@store_format:tp_shared_mqa",
                    None,
                )

        store_namespace = (
            f"@store_pp:{self.pp_size}@store_format:"
            f"rank_local_tp{self.tp_size}_layout_{cache_layout.name}"
        )
        requested_topology = (
            extra_config.get("prefill_tp_sizes")
            if lcm_store_tp_enabled
            else extra_config.get("store_tp_size")
        )
        logger.warning(
            "Mooncake heterogeneous-TP store sharing is disabled for "
            "Store TP configuration %r with KV layout %s; using a "
            "compatibility-namespaced rank-local store layout",
            requested_topology,
            cache_layout,
        )
        return None, store_namespace, None

    def _build_token_databases(
        self,
        metadata: KeyMetadata,
        layout_cls: type[TPShardedStoreLayout] | None,
    ) -> list[ChunkedTokenDatabase]:
        """Construct token databases and their Store layouts."""
        token_dbs: list[ChunkedTokenDatabase] = []
        for group_idx, group in enumerate(self._kv_cache_groups):
            hash_block_size = (
                self.hash_block_size
                if group.kv_cache_spec.prefix_cacheable
                else group.kv_cache_spec.block_size
            )
            group_tp_rank = self.tp_rank
            if layout_cls is None:
                group_tp_rank //= self._group_tp_replication_factors[group_idx]
            group_metadata = dataclasses.replace(
                metadata,
                group_id=group_idx,
                tp_rank=group_tp_rank,
            )
            store_layout: TPShardedStoreLayout | None = None
            if layout_cls is not None:
                assert self.store_tp_size is not None
                store_layout = layout_cls(
                    group_metadata,
                    group.kv_cache_spec.block_size,
                    hash_block_size,
                    local_tp_size=self.tp_size,
                    store_tp_size=self.store_tp_size,
                    tp_rank=self.tp_rank,
                    num_kv_heads=self.num_kv_head,
                )
            token_dbs.append(
                ChunkedTokenDatabase(
                    group_metadata,
                    group.kv_cache_spec.block_size,
                    hash_block_size=hash_block_size,
                    store_layout=store_layout,
                )
            )
        return token_dbs

    def get_mem_pool_context(self) -> AbstractContextManager | None:
        """Return a context manager for the custom MemPool, or None if
        no custom pool is configured."""
        if self._mem_pool is None:
            return None
        return torch.cuda.use_mem_pool(self._mem_pool)

    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(
            db.store_layout.lookup_key_prefixes(
                rank_namespaces(self._group_tp_replication_factors[g_idx])
            )
            for g_idx, db in enumerate(self.token_dbs)
        )

    def register_kv_caches(
        self,
        kv_caches: dict[str, 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
        use_group_regions = self._kv_cache_config.hisparse_host_num_blocks is not None

        if not use_group_regions:
            store_layer_names = {
                layer_name
                for group in self._kv_cache_groups
                for layer_name in group.layer_names
            }
            seen_storage_ptrs: set[int] = set()
            cache_tensors = [
                group_kernel_blocks(_repr_tensor(cache), self.num_blocks)
                for layer_name, cache in kv_caches.items()
                if layer_name in store_layer_names
            ]
            for cache in cache_tensors:
                cache_storage = cache.untyped_storage()
                base_addr = cache_storage.data_ptr()
                if base_addr in seen_storage_ptrs:
                    continue
                seen_storage_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,
                    )
            for db in self.token_dbs:
                db.store_layout.register_kv_caches(cache_tensors, self.num_blocks)

        registered_buffers: dict[int, int] = {}
        num_host_segments = 0
        num_device_segments = 0

        for group, db in zip(self._kv_cache_groups, self.token_dbs, strict=True):
            if not use_group_regions:
                continue
            missing_layers = [
                layer_name
                for layer_name in group.layer_names
                if layer_name not in kv_caches
            ]
            if missing_layers:
                raise ValueError(
                    f"Missing transferable KV caches for layers: {missing_layers}"
                )
            group_caches = [
                (layer_name, kv_caches[layer_name]) for layer_name in group.layer_names
            ]

            seen_group_ptrs: set[int] = set()
            addrs: list[int] = []
            block_lens: list[int] = []
            for layer_name, value in group_caches:
                cache = _repr_tensor(value)
                is_host_resident = group.host_resident
                if is_host_resident:
                    num_blocks = self._kv_cache_config.hisparse_host_num_blocks
                    assert num_blocks is not None
                else:
                    num_blocks = self._kv_cache_config.num_blocks
                cache = group_kernel_blocks(cache, num_blocks)
                cache_storage = cache.untyped_storage()
                if is_host_resident:
                    base_addr = cache.data_ptr()
                    region_len = cache.nbytes
                else:
                    base_addr = cache_storage.data_ptr()
                    region_len = cache_storage.nbytes()
                if region_len % num_blocks != 0:
                    raise ValueError(
                        f"KV cache region for {layer_name} has size {region_len}, "
                        f"which is not divisible by its {num_blocks} blocks."
                    )

                registered_len = registered_buffers.get(base_addr)
                if registered_len is None:
                    ret = self.store.register_buffer(base_addr, region_len)
                    if ret != 0:
                        mem_kind = "host" if is_host_resident else "device"
                        raise RuntimeError(
                            "Mooncake register_buffer failed for addr "
                            f"{base_addr:#x} len {region_len} ({mem_kind}): {ret}"
                        )
                    registered_buffers[base_addr] = region_len
                elif registered_len != region_len:
                    raise ValueError(
                        f"KV cache views at {base_addr:#x} expose inconsistent "
                        f"region sizes: {registered_len} and {region_len}."
                    )

                regions: list[tuple[int, int]] = []
                if not is_non_overlapping_and_dense(cache[0]):
                    for head_idx in range(cache.shape[1]):
                        head_cache = cache[:, head_idx]
                        assert is_non_overlapping_and_dense(head_cache[0])
                        regions.append(
                            (
                                head_cache.data_ptr(),
                                head_cache.stride(0) * head_cache.element_size(),
                            )
                        )
                elif cache.stride(0) * cache.element_size() * num_blocks == region_len:
                    regions.append((base_addr, region_len // num_blocks))
                else:
                    regions.append(
                        (cache.data_ptr(), cache.stride(0) * cache.element_size())
                    )

                for region_addr, block_len in regions:
                    if region_addr in seen_group_ptrs:
                        continue
                    seen_group_ptrs.add(region_addr)
                    addrs.append(region_addr)
                    block_lens.append(block_len)
                    if is_host_resident:
                        num_host_segments += 1
                    else:
                        num_device_segments += 1

            db.set_kv_caches_base_addr(addrs)
            db.set_block_len(block_lens)

        logger.info(
            "Registered KV caches: num_groups=%d, num_segments=%d (host=%d, device=%d)",
            len(self.token_dbs),
            num_host_segments + num_device_segments,
            num_host_segments,
            num_device_segments,
        )

        # Start transfer threads
        if self.can_put:
            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,
                group_participates=[
                    group.kv_cache_spec.prefix_cacheable
                    for group in self._kv_cache_groups
                ],
            )
            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,
                group_participates=[
                    group.kv_cache_spec.prefix_cacheable
                    for group in self._kv_cache_groups
                ],
                is_hma_required=self._is_hma_required,
            )
            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):
        """Issue async loads.

        Runs after the forward launch on steps without sync loads
        (SchedulerOutput.has_sync_kv_loads), keeping load submission off
        the critical path while preserving compute-I/O overlap.
        """
        if self._capacity_only:
            return

        for request in metadata.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."

    def wait_for_save(self, metadata: MooncakeStoreConnectorMetadata):
        """Issue async stores with CUDA event synchronization.

        Runs after the forward launch for compute-I/O overlap.
        """
        if self._capacity_only or not self.can_put:
            return

        current_event = None
        for request in metadata.requests:
            if request.can_save:
                current_event = torch.cuda.Event()
                current_event.record()
                break

        for request in metadata.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_request(request)

    def get_finished(
        self, finished_req_ids: set[str], meta: MooncakeStoreConnectorMetadata
    ) -> tuple[set[str], set[str]]:
        """Get completed send/recv request IDs.

        Loads are issued in start_load_kv() and stores in wait_for_save().
        """
        if self._capacity_only:
            return set(), set()

        if self.can_put:
            self._close_ended_store_requests(finished_req_ids, meta)

        # Blocks read by a store job are released by the scheduler when the job
        # reports back (see build_connector_worker_meta), so no request ever waits
        # on a `finished_sending` signal to get its blocks back.
        done_sending: set[str] = 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 get_transfer_results(
        self, finished_req_ids: set[str], meta: MooncakeStoreConnectorMetadata
    ) -> KVConnectorTransferResults:
        """Get completed sends/recvs plus requests whose remote KV load failed."""
        done_sending, done_recving = self.get_finished(finished_req_ids, meta)

        if self._capacity_only:
            return KVConnectorTransferResults(done_sending, done_recving)

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

        return KVConnectorTransferResults(
            finished_sending=done_sending,
            finished_recving=done_recving,
            failed_recving=failed_recving,
        )

    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 _close_ended_store_requests(
        self,
        finished_req_ids: set[str],
        meta: MooncakeStoreConnectorMetadata,
    ) -> None:
        """Retire the ledger entries of requests that finished or were preempted.

        An entry may only go once its jobs have drained, because they still read
        the resume offset it owns; a request that comes back after preemption
        then saves from the start rather than from where the last attempt got to.
        """
        assert self.kv_send_thread is not None

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

        for req_id in finished_req_ids | self.finished_store_req:
            if self.kv_send_thread.stored_requests.get(req_id):
                # Queued jobs still need the resume offset; retire on a later step.
                self.finished_store_req.add(req_id)
            else:
                self.finished_store_req.discard(req_id)
                self.kv_send_thread.delete_finished_stored_request(req_id)

    def build_connector_worker_meta(self) -> MooncakeStoreWorkerMetadata | None:
        if self.kv_send_thread is None:
            return None
        completed_saves = self.kv_send_thread.take_completed_saves()
        if not completed_saves:
            return None
        return MooncakeStoreWorkerMetadata(completed_saves=completed_saves)

    def lookup(
        self, num_tokens: int, block_hashes: Sequence[BlockHash]
    ) -> MooncakeLookupResult:
        """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 MooncakeLookupResult(0)

        token_len = self.coord.align_lookup_length(num_tokens)
        if not block_hashes or token_len <= 0:
            return MooncakeLookupResult(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):
            if not self._kv_cache_groups[g_idx].kv_cache_spec.prefix_cacheable:
                continue
            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 MooncakeLookupResult(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 MooncakeLookupResult(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,
        )
        _, 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 MooncakeLookupResult(0)
            _, hit_length = self.coord.find_longest_cache_hit(
                block_hashes,
                usable_length,
                cached_block_pool,
            )
        return MooncakeLookupResult(
            hit_length,
            self._tail_key_boundaries(
                block_hashes,
                hit_length,
                cached_block_pool,
            ),
        )

    def _tail_key_boundaries(
        self,
        block_hashes: Sequence[BlockHash],
        hit_length: int,
        cached_block_pool: ExternalCachedBlockPool,
    ) -> tuple[TailKeyBoundary, ...]:
        """Return the hash boundary used to store each group's tail block.

        With fine-grained prefix matching, ``hit_length`` may fall within a
        physical cache block and may not align with the hash boundary used to
        store that block. For each KV-cache group, return the token boundary
        whose hash was used as the store key.
        """
        if hit_length <= 0:
            return ()

        boundaries = []
        hit_boundary_hash_idx = hit_length // self.hash_block_size - 1
        for group_id, db in enumerate(self.token_dbs):
            if not self._kv_cache_groups[group_id].kv_cache_spec.prefix_cacheable:
                # Scratch groups are never stored, so they have no tail key.
                continue
            chunk_id = cdiv(hit_length, db.block_size) - 1
            boundary_tokens = hit_length
            contains_hit_boundary = cached_block_pool.contains(
                group_id, block_hashes[hit_boundary_hash_idx]
            )
            if not self.coord.enable_partial_hash_hits:
                assert contains_hit_boundary
            if not contains_hit_boundary:
                next_chunk_hash_idx = min(
                    (chunk_id + 1) * db.block_size // self.hash_block_size,
                    len(block_hashes),
                )
                for hash_idx in range(hit_boundary_hash_idx + 1, next_chunk_hash_idx):
                    if cached_block_pool.contains(group_id, block_hashes[hash_idx]):
                        boundary_tokens = (hash_idx + 1) * self.hash_block_size
                        break
                else:
                    raise AssertionError(
                        f"No tail key found for cache group {group_id} at "
                        f"hit length {hit_length}"
                    )
            boundaries.append(TailKeyBoundary(group_id, boundary_tokens))
        return tuple(boundaries)

    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 []

    @property
    def group_tp_replication_factors(self) -> tuple[int, ...]:
        return self._group_tp_replication_factors

    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
        deadline = time.monotonic() + 5.0
        for thread in (self.kv_send_thread, *self.kv_recv_threads):
            if thread is None:
                continue
            while thread.request_queue.unfinished_tasks and time.monotonic() < deadline:
                time.sleep(0.05)
            if thread.request_queue.unfinished_tasks:
                logger.warning(
                    "Mooncake store %s still has %d in-flight requests at "
                    "close; closing anyway.",
                    thread.name,
                    thread.request_queue.unfinished_tasks,
                )
        try:
            store.close()
        except Exception as e:
            logger.warning("Error closing MooncakeDistributedStore: %s", e)

_build_token_databases(metadata, layout_cls)

Construct token databases and their Store layouts.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
def _build_token_databases(
    self,
    metadata: KeyMetadata,
    layout_cls: type[TPShardedStoreLayout] | None,
) -> list[ChunkedTokenDatabase]:
    """Construct token databases and their Store layouts."""
    token_dbs: list[ChunkedTokenDatabase] = []
    for group_idx, group in enumerate(self._kv_cache_groups):
        hash_block_size = (
            self.hash_block_size
            if group.kv_cache_spec.prefix_cacheable
            else group.kv_cache_spec.block_size
        )
        group_tp_rank = self.tp_rank
        if layout_cls is None:
            group_tp_rank //= self._group_tp_replication_factors[group_idx]
        group_metadata = dataclasses.replace(
            metadata,
            group_id=group_idx,
            tp_rank=group_tp_rank,
        )
        store_layout: TPShardedStoreLayout | None = None
        if layout_cls is not None:
            assert self.store_tp_size is not None
            store_layout = layout_cls(
                group_metadata,
                group.kv_cache_spec.block_size,
                hash_block_size,
                local_tp_size=self.tp_size,
                store_tp_size=self.store_tp_size,
                tp_rank=self.tp_rank,
                num_kv_heads=self.num_kv_head,
            )
        token_dbs.append(
            ChunkedTokenDatabase(
                group_metadata,
                group.kv_cache_spec.block_size,
                hash_block_size=hash_block_size,
                store_layout=store_layout,
            )
        )
    return token_dbs

_close_ended_store_requests(finished_req_ids, meta)

Retire the ledger entries of requests that finished or were preempted.

An entry may only go once its jobs have drained, because they still read the resume offset it owns; a request that comes back after preemption then saves from the start rather than from where the last attempt got to.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
def _close_ended_store_requests(
    self,
    finished_req_ids: set[str],
    meta: MooncakeStoreConnectorMetadata,
) -> None:
    """Retire the ledger entries of requests that finished or were preempted.

    An entry may only go once its jobs have drained, because they still read
    the resume offset it owns; a request that comes back after preemption
    then saves from the start rather than from where the last attempt got to.
    """
    assert self.kv_send_thread is not None

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

    for req_id in finished_req_ids | self.finished_store_req:
        if self.kv_send_thread.stored_requests.get(req_id):
            # Queued jobs still need the resume offset; retire on a later step.
            self.finished_store_req.add(req_id)
        else:
            self.finished_store_req.discard(req_id)
            self.kv_send_thread.delete_finished_stored_request(req_id)

_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
    )

_select_store_layout(extra_config)

Select the opt-in TP layout and its Store namespace.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
def _select_store_layout(
    self, extra_config: dict[str, Any]
) -> tuple[int | None, str, type[TPShardedStoreLayout] | None]:
    """Select the opt-in TP layout and its Store namespace."""
    lcm_store_tp_enabled = extra_config.get("enable_store_tp_lcm") is True
    store_tp_requested = (
        lcm_store_tp_enabled or extra_config.get("store_tp_size") is not None
    )
    if not store_tp_requested:
        return None, "", None

    requested_store_tp_size = resolve_store_tp_size(extra_config)
    cache_layout = self.cache_config.get_resolved_kv_cache_layout()
    layout_cls: type[TPShardedStoreLayout] | None = {
        KVCacheLayout.LBHNC: LBHNCStoreLayout,
        KVCacheLayout.LBNHC: LBNHCStoreLayout,
    }.get(cache_layout)

    if (
        requested_store_tp_size is not None
        and requested_store_tp_size >= self.tp_size
        and requested_store_tp_size % self.tp_size == 0
        and self._supports_tp_sharded_store_layout(layout_cls, extra_config)
    ):
        assert layout_cls is not None
        if self.num_kv_head % requested_store_tp_size == 0:
            if layout_cls is LBNHCStoreLayout:
                logger.warning_once(
                    "Mooncake Store TP sharding is using the LBNHC (NHC) "
                    "KV cache layout, which creates many transfer segments "
                    "and may significantly reduce PUT/GET performance. Use "
                    "LBHNC (HNC) when supported by the attention backend."
                )
            return (
                requested_store_tp_size,
                layout_cls.shared_namespace(requested_store_tp_size, self.pp_size),
                layout_cls,
            )
        if self.num_kv_head == 1:
            logger.info(
                "Mooncake heterogeneous-TP store sharing uses the replicated "
                "MQA layout for store_tp_size=%d",
                requested_store_tp_size,
            )
            return (
                None,
                f"@store_pp:{self.pp_size}@store_format:tp_shared_mqa",
                None,
            )

    store_namespace = (
        f"@store_pp:{self.pp_size}@store_format:"
        f"rank_local_tp{self.tp_size}_layout_{cache_layout.name}"
    )
    requested_topology = (
        extra_config.get("prefill_tp_sizes")
        if lcm_store_tp_enabled
        else extra_config.get("store_tp_size")
    )
    logger.warning(
        "Mooncake heterogeneous-TP store sharing is disabled for "
        "Store TP configuration %r with KV layout %s; using a "
        "compatibility-namespaced rank-local store layout",
        requested_topology,
        cache_layout,
    )
    return None, store_namespace, None

_tail_key_boundaries(block_hashes, hit_length, cached_block_pool)

Return the hash boundary used to store each group's tail block.

With fine-grained prefix matching, hit_length may fall within a physical cache block and may not align with the hash boundary used to store that block. For each KV-cache group, return the token boundary whose hash was used as the store key.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
def _tail_key_boundaries(
    self,
    block_hashes: Sequence[BlockHash],
    hit_length: int,
    cached_block_pool: ExternalCachedBlockPool,
) -> tuple[TailKeyBoundary, ...]:
    """Return the hash boundary used to store each group's tail block.

    With fine-grained prefix matching, ``hit_length`` may fall within a
    physical cache block and may not align with the hash boundary used to
    store that block. For each KV-cache group, return the token boundary
    whose hash was used as the store key.
    """
    if hit_length <= 0:
        return ()

    boundaries = []
    hit_boundary_hash_idx = hit_length // self.hash_block_size - 1
    for group_id, db in enumerate(self.token_dbs):
        if not self._kv_cache_groups[group_id].kv_cache_spec.prefix_cacheable:
            # Scratch groups are never stored, so they have no tail key.
            continue
        chunk_id = cdiv(hit_length, db.block_size) - 1
        boundary_tokens = hit_length
        contains_hit_boundary = cached_block_pool.contains(
            group_id, block_hashes[hit_boundary_hash_idx]
        )
        if not self.coord.enable_partial_hash_hits:
            assert contains_hit_boundary
        if not contains_hit_boundary:
            next_chunk_hash_idx = min(
                (chunk_id + 1) * db.block_size // self.hash_block_size,
                len(block_hashes),
            )
            for hash_idx in range(hit_boundary_hash_idx + 1, next_chunk_hash_idx):
                if cached_block_pool.contains(group_id, block_hashes[hash_idx]):
                    boundary_tokens = (hash_idx + 1) * self.hash_block_size
                    break
            else:
                raise AssertionError(
                    f"No tail key found for cache group {group_id} at "
                    f"hit length {hit_length}"
                )
        boundaries.append(TailKeyBoundary(group_id, boundary_tokens))
    return tuple(boundaries)

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
    deadline = time.monotonic() + 5.0
    for thread in (self.kv_send_thread, *self.kv_recv_threads):
        if thread is None:
            continue
        while thread.request_queue.unfinished_tasks and time.monotonic() < deadline:
            time.sleep(0.05)
        if thread.request_queue.unfinished_tasks:
            logger.warning(
                "Mooncake store %s still has %d in-flight requests at "
                "close; closing anyway.",
                thread.name,
                thread.request_queue.unfinished_tasks,
            )
    try:
        store.close()
    except Exception as e:
        logger.warning("Error closing MooncakeDistributedStore: %s", e)

get_finished(finished_req_ids, meta)

Get completed send/recv request IDs.

Loads are issued in start_load_kv() and stores in wait_for_save().

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]]:
    """Get completed send/recv request IDs.

    Loads are issued in start_load_kv() and stores in wait_for_save().
    """
    if self._capacity_only:
        return set(), set()

    if self.can_put:
        self._close_ended_store_requests(finished_req_ids, meta)

    # Blocks read by a store job are released by the scheduler when the job
    # reports back (see build_connector_worker_meta), so no request ever waits
    # on a `finished_sending` signal to get its blocks back.
    done_sending: set[str] = 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

get_mem_pool_context()

Return a context manager for the custom MemPool, or None if no custom pool is configured.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
def get_mem_pool_context(self) -> AbstractContextManager | None:
    """Return a context manager for the custom MemPool, or None if
    no custom pool is configured."""
    if self._mem_pool is None:
        return None
    return torch.cuda.use_mem_pool(self._mem_pool)

get_transfer_results(finished_req_ids, meta)

Get completed sends/recvs plus requests whose remote KV load failed.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
def get_transfer_results(
    self, finished_req_ids: set[str], meta: MooncakeStoreConnectorMetadata
) -> KVConnectorTransferResults:
    """Get completed sends/recvs plus requests whose remote KV load failed."""
    done_sending, done_recving = self.get_finished(finished_req_ids, meta)

    if self._capacity_only:
        return KVConnectorTransferResults(done_sending, done_recving)

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

    return KVConnectorTransferResults(
        finished_sending=done_sending,
        finished_recving=done_recving,
        failed_recving=failed_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]
) -> MooncakeLookupResult:
    """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 MooncakeLookupResult(0)

    token_len = self.coord.align_lookup_length(num_tokens)
    if not block_hashes or token_len <= 0:
        return MooncakeLookupResult(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):
        if not self._kv_cache_groups[g_idx].kv_cache_spec.prefix_cacheable:
            continue
        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 MooncakeLookupResult(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 MooncakeLookupResult(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,
    )
    _, 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 MooncakeLookupResult(0)
        _, hit_length = self.coord.find_longest_cache_hit(
            block_hashes,
            usable_length,
            cached_block_pool,
        )
    return MooncakeLookupResult(
        hit_length,
        self._tail_key_boundaries(
            block_hashes,
            hit_length,
            cached_block_pool,
        ),
    )

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],
) -> 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
    use_group_regions = self._kv_cache_config.hisparse_host_num_blocks is not None

    if not use_group_regions:
        store_layer_names = {
            layer_name
            for group in self._kv_cache_groups
            for layer_name in group.layer_names
        }
        seen_storage_ptrs: set[int] = set()
        cache_tensors = [
            group_kernel_blocks(_repr_tensor(cache), self.num_blocks)
            for layer_name, cache in kv_caches.items()
            if layer_name in store_layer_names
        ]
        for cache in cache_tensors:
            cache_storage = cache.untyped_storage()
            base_addr = cache_storage.data_ptr()
            if base_addr in seen_storage_ptrs:
                continue
            seen_storage_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,
                )
        for db in self.token_dbs:
            db.store_layout.register_kv_caches(cache_tensors, self.num_blocks)

    registered_buffers: dict[int, int] = {}
    num_host_segments = 0
    num_device_segments = 0

    for group, db in zip(self._kv_cache_groups, self.token_dbs, strict=True):
        if not use_group_regions:
            continue
        missing_layers = [
            layer_name
            for layer_name in group.layer_names
            if layer_name not in kv_caches
        ]
        if missing_layers:
            raise ValueError(
                f"Missing transferable KV caches for layers: {missing_layers}"
            )
        group_caches = [
            (layer_name, kv_caches[layer_name]) for layer_name in group.layer_names
        ]

        seen_group_ptrs: set[int] = set()
        addrs: list[int] = []
        block_lens: list[int] = []
        for layer_name, value in group_caches:
            cache = _repr_tensor(value)
            is_host_resident = group.host_resident
            if is_host_resident:
                num_blocks = self._kv_cache_config.hisparse_host_num_blocks
                assert num_blocks is not None
            else:
                num_blocks = self._kv_cache_config.num_blocks
            cache = group_kernel_blocks(cache, num_blocks)
            cache_storage = cache.untyped_storage()
            if is_host_resident:
                base_addr = cache.data_ptr()
                region_len = cache.nbytes
            else:
                base_addr = cache_storage.data_ptr()
                region_len = cache_storage.nbytes()
            if region_len % num_blocks != 0:
                raise ValueError(
                    f"KV cache region for {layer_name} has size {region_len}, "
                    f"which is not divisible by its {num_blocks} blocks."
                )

            registered_len = registered_buffers.get(base_addr)
            if registered_len is None:
                ret = self.store.register_buffer(base_addr, region_len)
                if ret != 0:
                    mem_kind = "host" if is_host_resident else "device"
                    raise RuntimeError(
                        "Mooncake register_buffer failed for addr "
                        f"{base_addr:#x} len {region_len} ({mem_kind}): {ret}"
                    )
                registered_buffers[base_addr] = region_len
            elif registered_len != region_len:
                raise ValueError(
                    f"KV cache views at {base_addr:#x} expose inconsistent "
                    f"region sizes: {registered_len} and {region_len}."
                )

            regions: list[tuple[int, int]] = []
            if not is_non_overlapping_and_dense(cache[0]):
                for head_idx in range(cache.shape[1]):
                    head_cache = cache[:, head_idx]
                    assert is_non_overlapping_and_dense(head_cache[0])
                    regions.append(
                        (
                            head_cache.data_ptr(),
                            head_cache.stride(0) * head_cache.element_size(),
                        )
                    )
            elif cache.stride(0) * cache.element_size() * num_blocks == region_len:
                regions.append((base_addr, region_len // num_blocks))
            else:
                regions.append(
                    (cache.data_ptr(), cache.stride(0) * cache.element_size())
                )

            for region_addr, block_len in regions:
                if region_addr in seen_group_ptrs:
                    continue
                seen_group_ptrs.add(region_addr)
                addrs.append(region_addr)
                block_lens.append(block_len)
                if is_host_resident:
                    num_host_segments += 1
                else:
                    num_device_segments += 1

        db.set_kv_caches_base_addr(addrs)
        db.set_block_len(block_lens)

    logger.info(
        "Registered KV caches: num_groups=%d, num_segments=%d (host=%d, device=%d)",
        len(self.token_dbs),
        num_host_segments + num_device_segments,
        num_host_segments,
        num_device_segments,
    )

    # Start transfer threads
    if self.can_put:
        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,
            group_participates=[
                group.kv_cache_spec.prefix_cacheable
                for group in self._kv_cache_groups
            ],
        )
        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,
            group_participates=[
                group.kv_cache_spec.prefix_cacheable
                for group in self._kv_cache_groups
            ],
            is_hma_required=self._is_hma_required,
        )
        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)

Issue async loads.

Runs after the forward launch on steps without sync loads (SchedulerOutput.has_sync_kv_loads), keeping load submission off the critical path while preserving compute-I/O overlap.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
def start_load_kv(self, metadata: MooncakeStoreConnectorMetadata):
    """Issue async loads.

    Runs after the forward launch on steps without sync loads
    (SchedulerOutput.has_sync_kv_loads), keeping load submission off
    the critical path while preserving compute-I/O overlap.
    """
    if self._capacity_only:
        return

    for request in metadata.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."

wait_for_save(metadata)

Issue async stores with CUDA event synchronization.

Runs after the forward launch for compute-I/O overlap.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
def wait_for_save(self, metadata: MooncakeStoreConnectorMetadata):
    """Issue async stores with CUDA event synchronization.

    Runs after the forward launch for compute-I/O overlap.
    """
    if self._capacity_only or not self.can_put:
        return

    current_event = None
    for request in metadata.requests:
        if request.can_save:
            current_event = torch.cuda.Event()
            current_event.record()
            break

    for request in metadata.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_request(request)

_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}"
    )

resolve_store_tp_size(extra_config)

Resolve the common Store TP requested by connector config.

Source code in vllm/distributed/kv_transfer/kv_connector/v1/mooncake/store/worker.py
def resolve_store_tp_size(extra_config: dict[str, Any]) -> int | None:
    """Resolve the common Store TP requested by connector config."""
    if extra_config.get("enable_store_tp_lcm") is True:
        prefill_tp_sizes = extra_config.get("prefill_tp_sizes")
        if not isinstance(prefill_tp_sizes, list) or not prefill_tp_sizes:
            return None
        if any(
            type(tp_size) is not int or tp_size <= 0 for tp_size in prefill_tp_sizes
        ):
            return None
        return math.lcm(*prefill_tp_sizes)

    store_tp_size = extra_config.get("store_tp_size")
    return store_tp_size if type(store_tp_size) is int and store_tp_size > 0 else None