diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b084f06cb49..1e2ad5e63e5 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -793,13 +793,17 @@ jobs: build_targets: '' # Exercise the native UB target with its injected mock adapter. A # Debug build also catches ODR/link errors hidden by optimization. + # USE_UB_MOCK adds the test-only loopback URMA adapter for focused + # TENT and Store tests without UB hardware. - name: ub-mock cmake_flags: >- - -DUSE_CUDA=OFF -DUSE_UB=ON -DCMAKE_BUILD_TYPE=Debug - -DWITH_STORE=OFF -DWITH_STORE_RUST=OFF + -DUSE_CUDA=OFF -DUSE_UB=ON -DUSE_UB_MOCK=ON + -DCMAKE_BUILD_TYPE=Debug -DWITH_STORE_RUST=OFF need_cuda: false metrics_flags: '' - build_targets: '' + build_targets: >- + mooncake-transfer-engine/all + store_tent_ub_mock_test # Compile against stub ACL headers and embed host-only ACL stubs in # transfer_engine for Rust checks; no CANN, NPU, or libmf_smem is required. - name: memfabric-mock @@ -912,6 +916,15 @@ jobs: -R '^transfer_task_tent_shared_segment_test$' shell: bash + # The hugepage case skips itself when the runner grants no hugepages. + - name: Test Store over the TENT UB loopback adapter + if: matrix.name == 'ub-mock' + run: | + sudo sysctl -w vm.nr_hugepages=64 || true + ctest --test-dir build-tent --output-on-failure --no-tests=error \ + -R '^store_tent_ub_mock_test$' + shell: bash + # Only run tests on the cuda-off leg. GitHub runners have no real GPU; # with USE_CUDA=ON tent's cuda_probe hits the CUDA stub library at # runtime and drives some dispatch paths past the fake objects the diff --git a/CMakeLists.txt b/CMakeLists.txt index c8dfac56444..8f710b59f88 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -36,6 +36,12 @@ endif() option(WITH_STORE "build mooncake store library and sample code" ON) option(WITH_STORE_GO "build Go bindings for mooncake store" OFF) option(WITH_CONDUCTOR "build mooncake conductor service" OFF) +option(WITH_CONDUCTOR_GO "build Go bindings for mooncake conductor" OFF) +option(WITH_CONDUCTOR_C_SHARED + "build the conductor client C ABI shared library" OFF) +if((WITH_CONDUCTOR_GO OR WITH_CONDUCTOR_C_SHARED) AND NOT WITH_CONDUCTOR) + message(FATAL_ERROR "Conductor language bindings require WITH_CONDUCTOR=ON") +endif() option(WITH_P2P_STORE "build p2p store library and sample code" OFF) option(WITH_RUST_EXAMPLE "build the Rust interface and sample code for the transfer engine" OFF) diff --git a/README.md b/README.md index a0bb467633b..247fc736fb9 100644 --- a/README.md +++ b/README.md @@ -210,7 +210,56 @@ Mooncake integrates with [vLLM](https://github.com/vllm-project/vllm) to acceler

馃寪 Ecosystem Integrations

-Mooncake connects inference engines, cache middleware, RL systems, and deployment tools. The directory below links to upstream guides and implementations for each integration. +Mooncake connects inference engines, cache middleware, RL systems, and deployment tools. Click a logo or a name to open the upstream project. Projects without a published logo are listed by name. + +

+ SGLang + vLLM + TokenSpeed + LMDeploy + vLLM-Ascend + FastDeploy +
+ xLLM + Chitu + ATOM + SGLang-Omni + vLLM-Omni + LightX2V +
+ LMCache + UCM + GPUStack + mstar + PyTorch + Dynamo +
+ llm-d + slime + Miles + Awex + SpecForge +
+ TensorRT-LLM 路 + FlexKV 路 + Tair KVCache 路 + NIXL 路 + Infera 路 + Fluxon 路 + RBG 路 + SMG 路 + srt-slurm 路 + verl 路 + SkyRL 路 + prime-rl 路 + NeMo RL 路 + UniRL 路 + TransferQueue 路 + checkpoint-engine 路 + TorchTitan 路 + TorchSpec 路 + Speculators +

Integration directory @@ -219,34 +268,50 @@ Mooncake connects inference engines, cache middleware, RL systems, and deploymen | Project | Mooncake components | Integration use cases | Guide or implementation | | --- | --- | --- | --- | -| SGLang | TE, Store, EP/PG | PD/EPD transfer, HiCache, multimodal embedding caching, weight synchronization, and Elastic EP | [Integration guide](https://kvcache-ai.github.io/Mooncake/deployment/integrations/sglang/index.html), [Elastic EP](https://github.com/sgl-project/sglang/pull/10423) | -| vLLM | TE, Store | PD transfer, shared KV pooling, encoder-cache transfer, and cross-encoder embedding reuse | [PD connector](https://docs.vllm.ai/en/latest/features/mooncake_connector_usage/), [Store connector](https://docs.vllm.ai/en/latest/features/mooncake_store_connector_usage/), [encoder connector](https://docs.vllm.ai/en/latest/features/mooncake_ec_connector_usage/) | -| TokenSpeed | TE, Store | PD/EPD transfer and Store-backed L3 beneath the host KV cache | [Server configuration](https://github.com/lightseekorg/tokenspeed/blob/main/docs/configuration/server.md) | -| TensorRT-LLM | TE, Store | PD transfer and shared KV pooling through the KVCMv2 Store connector merged into main | [TE implementation](https://github.com/NVIDIA/TensorRT-LLM/tree/main/cpp/tensorrt_llm/executor/cache_transmission/mooncake_utils), [Store connector](https://github.com/NVIDIA/TensorRT-LLM/pull/19171) | -| LMDeploy | TE, Store | PD transfer and cross-instance KV prefix reuse | [TE guide](https://kvcache-ai.github.io/Mooncake/deployment/integrations/lmdeploy.html), [Store connector](https://github.com/InternLM/lmdeploy/pull/4903) | -| vLLM-Ascend | TE, Store | NPU PD transfer and KV pooling through AscendStoreConnector | [PD deployment](https://github.com/vllm-project/vllm-ascend/blob/main/docs/source/tutorials/features/pd_disaggregation_mooncake_multi_node.md), [KV pool](https://github.com/vllm-project/vllm-ascend/blob/main/docs/source/user_guide/feature_guide/kv_cache_pool_ascend_store.md) | -| FastDeploy | Store | Global KV pooling and cache reuse in PD serving | [Global cache pooling](https://github.com/PaddlePaddle/FastDeploy/blob/develop/docs/features/global_cache_pooling.md) | -| xLLM | TE, Store | KV transfer and distributed cache management | [KV transfer backends](https://github.com/jd-opensource/xllm/tree/main/xllm/core/kv_cache/transfer) | -| Chitu | TE | Multi-prefill/multi-decode KV transfer over RDMA | [PD disaggregation](https://github.com/thu-pacman/chitu/blob/public-main/chitu/distributed/pd_disaggregation/README.md) | -| LMCache | TE, Store | Remote KV storage, a native MP L2 adapter, and P2P cache sharing | [Store guide](https://docs.lmcache.ai/kv_cache/storage_backends/mooncake.html), [MP adapter](https://docs.lmcache.ai/mp/l2_storage.html#mooncake-store-mooncake-store-native-connector), [P2P backend](https://github.com/LMCache/LMCache/pull/4182) | -| FlexKV | TE, Store | Distributed cache reuse and a content-addressed REMOTE tier | [Distributed reuse](https://github.com/taco-project/FlexKV/blob/main/docs/dist_reuse/README_en.md), [Store backend](https://github.com/taco-project/FlexKV/pull/231) | -| NIXL | TE | Mooncake transport plugin for NIXL data movement | [Plugin guide](https://github.com/ai-dynamo/nixl/blob/main/src/plugins/mooncake/README.md) | -| Dynamo | Store via SGLang HiCache | Shared-pool awareness and event-driven KV cache routing | [HiCache integration](https://github.com/ai-dynamo/dynamo/blob/main/docs/fern/pages/developer-guide/knowledge-base/modular-components/backends/sglang/hicache.md) | -| llm-d | TE, Store via vLLM | Kubernetes PD serving and tiered KV cache offloading | [PD integration](https://github.com/llm-d/llm-d/pull/1511), [Tiered prefix cache](https://github.com/llm-d/llm-d/tree/main/guides/tiered-prefix-cache) | -| RBG | TE, Store via inference engines | Role-based orchestration of Store, PD transfer, and cache reuse | [Deployment examples](https://github.com/sgl-project/rbg/tree/main/examples/inference/ecosystem/mooncake) | -| srt-slurm | TE, Store via inference engines | Slurm deployment and Mooncake service configuration | [Mooncake services](https://github.com/NVIDIA/srt-slurm/blob/main/docs/mooncake-kv-store.md) | -| NeMo RL | Store via TransferQueue | Rollout-to-training data exchange with optional GDR client transfers | [Data plane](https://github.com/NVIDIA-NeMo/RL/blob/main/nemo_rl/data_plane/README.md), [GDR support](https://github.com/NVIDIA-NeMo/RL/pull/3501) | -| TransferQueue | Store | RL tensor/object storage, GDR transfers, and SSD offloading | [Store client](https://github.com/Ascend/TransferQueue/blob/main/transfer_queue/storage/clients/mooncake_client.py), [GDR guide](https://github.com/Ascend/TransferQueue/blob/main/docs/storage_backends/mooncake_gdr.md) | -| verl | TE | Checkpoint-engine backend for trainer-to-rollout weight synchronization | [Mooncake backend](https://github.com/verl-project/verl/blob/main/verl/checkpoint_engine/mooncake_checkpoint_engine.py) | -| checkpoint-engine | TE | Peer-to-peer model-weight distribution and updates | [P2P backend](https://github.com/MoonshotAI/checkpoint-engine) | -| Miles | Store | Rollout-to-training data transfer | [Rollout transfer guide](https://github.com/radixark/miles/blob/main/docs/advanced/mooncake-rollout-transfer.md) | -| TorchSpec | Store | Hidden-state exchange between inference and draft-model training | [Training architecture](https://github.com/torchspec-project/TorchSpec) | -| Speculators | Store | Hidden-state exchange for distributed online draft-model training | [Hidden-state connectors](https://github.com/vllm-project/speculators/tree/main/hs_connectors) | -| vLLM-Omni | TE, Store | Data exchange between multimodal pipeline stages | [Omni connectors](https://github.com/vllm-project/vllm-omni/tree/main/vllm_omni/distributed/omni_connectors/connectors) | -| SGLang-Omni | TE | Cross-stage tensor and blob transfer between thinker, talker, codec, and vocoder stages | [SGLang-Omni](https://github.com/sgl-project/sglang-omni) | -| LightX2V | TE | Encoder/transformer disaggregation for video generation | [Transfer backend](https://github.com/ModelTC/LightX2V/blob/main/lightx2v/disagg/mooncake.py) | -| slime | TE via SGLang | PD-disaggregated rollout serving | [RL serving architecture](https://github.com/THUDM/slime/blob/main/docs/en/advanced/rl-systems.md) | -| ATOM | TE, Store | Shared KV cache pooling and efficient KV transfer | [Integration blog](https://kvcache.ai/blog/atom-meets-mooncake/) | +| [SGLang](https://github.com/sgl-project/sglang) | TE, Store, EP/PG | PD/EPD transfer, HiCache, multimodal embedding caching, weight synchronization, and Elastic EP | [Integration guide](https://kvcache-ai.github.io/Mooncake/deployment/integrations/sglang/index.html), [Elastic EP](https://github.com/sgl-project/sglang/pull/10423) | +| [vLLM](https://github.com/vllm-project/vllm) | TE, Store | PD transfer, shared KV pooling, encoder-cache transfer, and cross-encoder embedding reuse | [PD connector](https://docs.vllm.ai/en/latest/features/mooncake_connector_usage/), [Store connector](https://docs.vllm.ai/en/latest/features/mooncake_store_connector_usage/), [encoder connector](https://docs.vllm.ai/en/latest/features/mooncake_ec_connector_usage/) | +| [TokenSpeed](https://github.com/lightseekorg/tokenspeed) | TE, Store | PD/EPD transfer and Store-backed L3 beneath the host KV cache | [Server configuration](https://github.com/lightseekorg/tokenspeed/blob/main/docs/configuration/server.md) | +| [TensorRT-LLM](https://github.com/NVIDIA/TensorRT-LLM) | TE, Store | PD transfer and shared KV pooling through the KVCMv2 Store connector merged into main | [TE implementation](https://github.com/NVIDIA/TensorRT-LLM/tree/main/cpp/tensorrt_llm/executor/cache_transmission/mooncake_utils), [Store connector](https://github.com/NVIDIA/TensorRT-LLM/pull/19171) | +| [LMDeploy](https://github.com/InternLM/lmdeploy) | TE, Store | PD transfer and cross-instance KV prefix reuse | [TE guide](https://kvcache-ai.github.io/Mooncake/deployment/integrations/lmdeploy.html), [Store connector](https://github.com/InternLM/lmdeploy/pull/4903) | +| [vLLM-Ascend](https://github.com/vllm-project/vllm-ascend) | TE, Store | NPU PD transfer and KV pooling through AscendStoreConnector | [PD deployment](https://github.com/vllm-project/vllm-ascend/blob/main/docs/source/tutorials/features/pd_disaggregation_mooncake_multi_node.md), [KV pool](https://github.com/vllm-project/vllm-ascend/blob/main/docs/source/user_guide/feature_guide/kv_cache_pool_ascend_store.md) | +| [FastDeploy](https://github.com/PaddlePaddle/FastDeploy) | Store | Global KV pooling and cache reuse in PD serving | [Global cache pooling](https://github.com/PaddlePaddle/FastDeploy/blob/develop/docs/features/global_cache_pooling.md) | +| [xLLM](https://github.com/jd-opensource/xllm) | TE, Store | KV transfer and distributed cache management | [KV transfer backends](https://github.com/jd-opensource/xllm/tree/main/xllm/core/kv_cache/transfer) | +| [Chitu](https://github.com/thu-pacman/chitu) | TE | Multi-prefill/multi-decode KV transfer over RDMA | [PD disaggregation](https://github.com/thu-pacman/chitu/blob/public-main/chitu/distributed/pd_disaggregation/README.md) | +| [ATOM](https://github.com/ROCm/ATOM) | TE, Store | Shared KV cache pooling and efficient KV transfer | [Integration blog](https://kvcache.ai/blog/atom-meets-mooncake/), [PD connector](https://github.com/ROCm/ATOM/tree/main/atom/kv_transfer/disaggregation/mooncake), [Store offload](https://github.com/ROCm/ATOM/tree/main/atom/kv_transfer/offload/mooncake_store) | +| [SGLang-Omni](https://github.com/sgl-project/sglang-omni) | TE | Cross-stage tensor and blob transfer between thinker, talker, codec, and vocoder stages | [Relay backend](https://github.com/sgl-project/sglang-omni/blob/main/sglang_omni/relay/mooncake.py) | +| [vLLM-Omni](https://github.com/vllm-project/vllm-omni) | TE, Store | Data exchange between multimodal pipeline stages | [Omni connectors](https://github.com/vllm-project/vllm-omni/tree/main/vllm_omni/distributed/omni_connectors/connectors) | +| [LightX2V](https://github.com/ModelTC/LightX2V) | TE | Encoder/transformer disaggregation for video generation | [Transfer backend](https://github.com/ModelTC/LightX2V/blob/main/lightx2v/disagg/mooncake.py) | +| [mstar](https://github.com/mstar-project/mstar) | TE | RDMA tensor transport between serving stages | [Tensor transport](https://github.com/mstar-project/mstar/blob/main/mstar/communication/tensors.py) | +| [Infera](https://github.com/AMD-AGI/Infera) | TE via SGLang | PD disaggregation over Mooncake on ROCm | [1P1D example](https://github.com/AMD-AGI/Infera/blob/main/manual/examples/k8s_pd_1p1d_mooncake.md) | +| [LMCache](https://github.com/LMCache/LMCache) | TE, Store | Remote KV storage, a native MP L2 adapter, and P2P cache sharing | [Store guide](https://docs.lmcache.ai/kv_cache/storage_backends/mooncake.html), [MP adapter](https://docs.lmcache.ai/mp/l2_storage.html#mooncake-store-mooncake-store-native-connector), [P2P backend](https://github.com/LMCache/LMCache/pull/4182) | +| [FlexKV](https://github.com/taco-project/FlexKV) | TE, Store | Distributed cache reuse and a content-addressed REMOTE tier | [Distributed reuse](https://github.com/taco-project/FlexKV/blob/main/docs/dist_reuse/README_en.md), [Store backend](https://github.com/taco-project/FlexKV/pull/231) | +| [Tair KVCache](https://github.com/alibaba/tair-kvcache) | Store | Mooncake Store as a data-storage backend for the KV Cache Manager | [Store backend](https://github.com/alibaba/tair-kvcache/blob/main/kv_cache_manager/data_storage/mooncake_backend.cc) | +| [UCM](https://github.com/ModelEngine-Group/unified-cache-management) | Store | Shared KV store and PD transport for Ascend inference | [Store pipeline](https://ucm.readthedocs.io/en/latest/developer-guide/cache-configuration/mooncake/), [PD transport](https://ucm.readthedocs.io/en/latest/user-guide/capabilities/pd-disaggregation/distributed/) | +| [Fluxon](https://github.com/Tele-AI/Fluxon) | Store | KV cache client backed by Mooncake Store | [Mooncake client](https://github.com/Tele-AI/Fluxon/blob/main/fluxon_py/kvclient/mooncake.py) | +| [NIXL](https://github.com/ai-dynamo/nixl) | TE | Mooncake transport plugin for NIXL data movement | [Plugin guide](https://github.com/ai-dynamo/nixl/blob/main/src/plugins/mooncake/README.md) | +| [PyTorch](https://github.com/pytorch/pytorch) | TE | Mooncake transport for point-to-point tensor transfer in `torch.distributed._transport` | [Transport](https://github.com/pytorch/pytorch/tree/main/torch/distributed/_transport/mooncake) | +| [Dynamo](https://github.com/ai-dynamo/dynamo) | Store via SGLang HiCache | Shared-pool awareness and event-driven KV cache routing | [HiCache integration](https://github.com/ai-dynamo/dynamo/blob/main/docs/fern/pages/developer-guide/knowledge-base/modular-components/backends/sglang/hicache.md) | +| [SMG](https://github.com/smg-project/smg) | TE via vLLM | KV-aware routing for Mooncake PD transfer | [PD transfer](https://github.com/smg-project/smg/blob/main/e2e_test/router/test_pd_mooncake.py) | +| [llm-d](https://github.com/llm-d/llm-d) | TE, Store via vLLM | Kubernetes PD serving and tiered KV cache offloading | [PD integration](https://github.com/llm-d/llm-d/pull/1511), [Tiered prefix cache](https://github.com/llm-d/llm-d/tree/main/guides/tiered-prefix-cache) | +| [GPUStack](https://github.com/gpustack/gpustack) | TE, Store | Managed Mooncake KV pools and PD disaggregation | [Cache backend](https://docs.gpustack.ai/gpustack-operator/v0.10.0/docs/modules/kv-cache/backend/), [PD disaggregation](https://docs.gpustack.ai/2.3/user-guide/pd-disaggregation/) | +| [RBG](https://github.com/sgl-project/rbg) | TE, Store via inference engines | Role-based orchestration of Store, PD transfer, and cache reuse | [Deployment examples](https://github.com/sgl-project/rbg/tree/main/examples/inference/ecosystem/mooncake) | +| [srt-slurm](https://github.com/NVIDIA/srt-slurm) | TE, Store via inference engines | Slurm deployment and Mooncake service configuration | [Mooncake services](https://github.com/NVIDIA/srt-slurm/blob/main/docs/mooncake-kv-store.md) | +| [verl](https://github.com/verl-project/verl) | TE | Checkpoint-engine backend for trainer-to-rollout weight synchronization | [Mooncake backend](https://github.com/verl-project/verl/blob/main/verl/checkpoint_engine/mooncake_checkpoint_engine.py) | +| [slime](https://github.com/THUDM/slime) | TE via SGLang | PD-disaggregated rollout serving | [RL serving architecture](https://github.com/THUDM/slime/blob/main/docs/en/advanced/rl-systems.md) | +| [Miles](https://github.com/radixark/miles) | Store | Rollout-to-training data transfer | [Rollout transfer guide](https://github.com/radixark/miles/blob/main/docs/advanced/mooncake-rollout-transfer.md) | +| [SkyRL](https://github.com/skyrl-project/SkyRL) | TE, Store via vLLM | PD transfer and shared KV offload for RL inference | [Inference guide](https://github.com/skyrl-project/SkyRL/blob/main/.agents/docs/inference.md) | +| [prime-rl](https://github.com/PrimeIntellect-ai/prime-rl) | Store | Shared KV offload across inference nodes | [Inference guide](https://github.com/PrimeIntellect-ai/prime-rl/blob/main/docs/inference.md) | +| [UniRL](https://github.com/Tencent-Hunyuan/UniRL) | Store via TransferQueue | Rollout data exchange over Mooncake RDMA | [Data plane](https://github.com/Tencent-Hunyuan/UniRL/blob/main/unirl/distributed/README.md) | +| [TorchTitan](https://github.com/pytorch/torchtitan) | Store via SGLang HiCache | Mooncake Store master for RL generators | [Store master](https://github.com/pytorch/torchtitan/blob/main/torchtitan/rl/generator/mooncake_master.py) | +| [NeMo RL](https://github.com/NVIDIA-NeMo/RL) | Store via TransferQueue | Rollout-to-training data exchange with optional GDR client transfers | [Data plane](https://github.com/NVIDIA-NeMo/RL/blob/main/nemo_rl/data_plane/README.md), [GDR support](https://github.com/NVIDIA-NeMo/RL/pull/3501) | +| [TransferQueue](https://github.com/Ascend/TransferQueue) | Store | RL tensor/object storage, GDR transfers, and SSD offloading | [Store client](https://github.com/Ascend/TransferQueue/blob/main/transfer_queue/storage/clients/mooncake_client.py), [GDR guide](https://github.com/Ascend/TransferQueue/blob/main/docs/storage_backends/mooncake_gdr.md) | +| [checkpoint-engine](https://github.com/MoonshotAI/checkpoint-engine) | TE | Peer-to-peer model-weight distribution and updates | [P2P backend](https://github.com/MoonshotAI/checkpoint-engine) | +| [Awex](https://github.com/inclusionAI/Awex) | TE | Training-to-inference weight synchronization | [Mooncake backend](https://github.com/inclusionAI/Awex#mooncake-weight-transfer) | +| [TorchSpec](https://github.com/lightseekorg/TorchSpec) | Store | Hidden-state exchange between inference and draft-model training | [Training architecture](https://github.com/lightseekorg/TorchSpec) | +| [Speculators](https://github.com/vllm-project/speculators) | Store | Hidden-state exchange for distributed online draft-model training | [Hidden-state connectors](https://github.com/vllm-project/speculators/tree/main/hs_connectors) | +| [SpecForge](https://github.com/sgl-project/SpecForge) | Store | Hidden-state exchange for online draft-model training | [Store data plane](https://github.com/sgl-project/SpecForge/blob/main/specforge/runtime/data_plane/mooncake_store.py) | + +The Dynamo entry describes SGLang HiCache shared-cache routing. NeMo RL's GDR path changes client-side tensor transfers; queued objects remain in Mooncake-managed host memory.
@@ -256,7 +321,7 @@ Mooncake supports hardware backends across accelerator vendors, cloud fabrics, a

- Supported hardware ecosystem: NVIDIA, Huawei, AMD, Cambricon, Moore Threads, AWS, MetaX, T-Head, Alibaba Cloud, Sunrise, Hygon, Biren Technology, Intel, Google, HPE, Iluvatar CoreX, FlagOS. + Supported hardware ecosystem: NVIDIA, Huawei, AMD, Cambricon, Moore Threads, AWS, MetaX, T-Head, Alibaba Cloud, Sunrise, Hygon, Biren Technology, Intel, Google, HPE, Iluvatar CoreX, FlagOS, Enflame.

*Each logo has equal display space; placement does not indicate ranking.* diff --git a/docs/source/performance/mooncake/tebench.md b/docs/source/performance/mooncake/tebench.md index d1b1805c5c3..07610edb5f7 100644 --- a/docs/source/performance/mooncake/tebench.md +++ b/docs/source/performance/mooncake/tebench.md @@ -174,7 +174,10 @@ and the data fill and verify of `--check_consistency`. `Avg Tx`, `P99 Tx`, `P999 Tx`, and `Avg Inst GB/s` time only the transfer itself, from submit to completion. -A short (~1 second) warmup phase is executed before measurements begin. +Each case warms up for `--warmup_ms` milliseconds (1000 by default) before +measurements begin. Use `--warmup_ms=0` to measure without warmup, including +the cost of the first transfer. All worker threads still synchronize before +starting the measured workload. ### 4.1 QoS Metrics Baseline @@ -301,7 +304,7 @@ When set, each completed transfer appends one JSON line: | Field | Meaning | | ----- | ------- | | `block_size`, `batch_size` | Shape of the transfer, identifying the sweep point | -| `warmup` | `true` for transfers in the 1 s warmup before measurement | +| `warmup` | `true` for transfers in the configured warmup before measurement | | `submit_us` | Time in `submitTransfer`, in microseconds with ns precision | | `wait_us` | Time from submit return until the batch reports COMPLETED, in microseconds with ns precision | | `polls` | Number of status polls in that wait | @@ -396,6 +399,7 @@ Example: * `--start_batch_size`, `--max_batch_size` : batch size sweep (powers of two) * `--start_num_threads`, `--max_num_threads` : thread sweep (powers of two) * `--duration` : measurement time per case (seconds) +* `--warmup_ms` : warmup time per case (milliseconds; default 1000, 0 disables) Each thread owns one fixed region in its local buffer and one in its target buffer, sized for the largest operation (`max_block_size 脳 max_batch_size`, or diff --git a/image/ecosystem/atom.png b/image/ecosystem/atom.png new file mode 100644 index 00000000000..67149c0116c Binary files /dev/null and b/image/ecosystem/atom.png differ diff --git a/image/ecosystem/awex.png b/image/ecosystem/awex.png new file mode 100644 index 00000000000..245ce099066 Binary files /dev/null and b/image/ecosystem/awex.png differ diff --git a/image/ecosystem/chitu.png b/image/ecosystem/chitu.png new file mode 100644 index 00000000000..dbdc83b4242 Binary files /dev/null and b/image/ecosystem/chitu.png differ diff --git a/image/ecosystem/dynamo.png b/image/ecosystem/dynamo.png new file mode 100644 index 00000000000..ac5f6d0aeac Binary files /dev/null and b/image/ecosystem/dynamo.png differ diff --git a/image/ecosystem/fastdeploy.png b/image/ecosystem/fastdeploy.png new file mode 100644 index 00000000000..9cea5eb8f00 Binary files /dev/null and b/image/ecosystem/fastdeploy.png differ diff --git a/image/ecosystem/gpustack.png b/image/ecosystem/gpustack.png new file mode 100644 index 00000000000..b9fe94a9779 Binary files /dev/null and b/image/ecosystem/gpustack.png differ diff --git a/image/ecosystem/lightx2v.png b/image/ecosystem/lightx2v.png new file mode 100644 index 00000000000..6331d0af93a Binary files /dev/null and b/image/ecosystem/lightx2v.png differ diff --git a/image/ecosystem/llm-d.png b/image/ecosystem/llm-d.png new file mode 100644 index 00000000000..50d82b2b57b Binary files /dev/null and b/image/ecosystem/llm-d.png differ diff --git a/image/ecosystem/lmcache.png b/image/ecosystem/lmcache.png new file mode 100644 index 00000000000..a3cd2c18eed Binary files /dev/null and b/image/ecosystem/lmcache.png differ diff --git a/image/ecosystem/lmdeploy.png b/image/ecosystem/lmdeploy.png new file mode 100644 index 00000000000..b97616a6c22 Binary files /dev/null and b/image/ecosystem/lmdeploy.png differ diff --git a/image/ecosystem/miles.png b/image/ecosystem/miles.png new file mode 100644 index 00000000000..b8791e0d32a Binary files /dev/null and b/image/ecosystem/miles.png differ diff --git a/image/ecosystem/mstar.png b/image/ecosystem/mstar.png new file mode 100644 index 00000000000..3aeac45f3e5 Binary files /dev/null and b/image/ecosystem/mstar.png differ diff --git a/image/ecosystem/pytorch.png b/image/ecosystem/pytorch.png new file mode 100644 index 00000000000..57a4164b326 Binary files /dev/null and b/image/ecosystem/pytorch.png differ diff --git a/image/ecosystem/sglang-omni.png b/image/ecosystem/sglang-omni.png new file mode 100644 index 00000000000..6504f6c7332 Binary files /dev/null and b/image/ecosystem/sglang-omni.png differ diff --git a/image/ecosystem/sglang.png b/image/ecosystem/sglang.png new file mode 100644 index 00000000000..ad088e4941b Binary files /dev/null and b/image/ecosystem/sglang.png differ diff --git a/image/ecosystem/slime.png b/image/ecosystem/slime.png new file mode 100644 index 00000000000..8de0600fab2 Binary files /dev/null and b/image/ecosystem/slime.png differ diff --git a/image/ecosystem/specforge.png b/image/ecosystem/specforge.png new file mode 100644 index 00000000000..2a7ce51645c Binary files /dev/null and b/image/ecosystem/specforge.png differ diff --git a/image/ecosystem/tokenspeed.png b/image/ecosystem/tokenspeed.png new file mode 100644 index 00000000000..7096db863b0 Binary files /dev/null and b/image/ecosystem/tokenspeed.png differ diff --git a/image/ecosystem/ucm.png b/image/ecosystem/ucm.png new file mode 100644 index 00000000000..29e0484d8dd Binary files /dev/null and b/image/ecosystem/ucm.png differ diff --git a/image/ecosystem/vllm-ascend.png b/image/ecosystem/vllm-ascend.png new file mode 100644 index 00000000000..3f1de324a6b Binary files /dev/null and b/image/ecosystem/vllm-ascend.png differ diff --git a/image/ecosystem/vllm-omni.png b/image/ecosystem/vllm-omni.png new file mode 100644 index 00000000000..3b4f4828190 Binary files /dev/null and b/image/ecosystem/vllm-omni.png differ diff --git a/image/ecosystem/vllm.png b/image/ecosystem/vllm.png new file mode 100644 index 00000000000..35385f22d7b Binary files /dev/null and b/image/ecosystem/vllm.png differ diff --git a/image/ecosystem/xllm.png b/image/ecosystem/xllm.png new file mode 100644 index 00000000000..614445de420 Binary files /dev/null and b/image/ecosystem/xllm.png differ diff --git a/image/hardwares/enflame_logo.png b/image/hardwares/enflame_logo.png new file mode 100644 index 00000000000..d50b16b69d8 Binary files /dev/null and b/image/hardwares/enflame_logo.png differ diff --git a/image/hardwares/supported_hardware.png b/image/hardwares/supported_hardware.png index 579a0746217..27dbdf87ac3 100644 Binary files a/image/hardwares/supported_hardware.png and b/image/hardwares/supported_hardware.png differ diff --git a/mooncake-common/common.cmake b/mooncake-common/common.cmake index 1e99270fbac..0217b4821c3 100644 --- a/mooncake-common/common.cmake +++ b/mooncake-common/common.cmake @@ -113,6 +113,13 @@ option(USE_MNNVL "option for using Multi-Node NVLink transport" OFF) option(USE_CXL "option for using CXL protocol" OFF) option(USE_EFA "option for using AWS EFA transport" OFF) option(USE_UB "option for using UB protocol transport" OFF) +option( + USE_UB_MOCK + "test-only: build TENT UB with an in-process loopback URMA adapter, enabled at runtime by MC_TENT_UB_MOCK=1; never use in production builds" + OFF) +if(USE_UB_MOCK AND NOT USE_UB) + message(FATAL_ERROR "USE_UB_MOCK requires USE_UB=ON") +endif() option(USE_SUNRISE "option for enabling gpu features for Sunrise GPU with Tang runtime" OFF) option(USE_ENFLAME diff --git a/mooncake-conductor/CMakeLists.txt b/mooncake-conductor/CMakeLists.txt index 1abbcfc6270..37a47991cf0 100644 --- a/mooncake-conductor/CMakeLists.txt +++ b/mooncake-conductor/CMakeLists.txt @@ -14,6 +14,9 @@ endif() find_package(Threads REQUIRED) find_package(OpenSSL REQUIRED COMPONENTS Crypto) +option(WITH_CONDUCTOR_GO "build Go bindings for mooncake conductor" OFF) +option(WITH_CONDUCTOR_C_SHARED + "build the conductor client C ABI shared library" OFF) # Standalone builds own their dependencies; the top-level build provides this # target before adding Conductor and Store. @@ -133,6 +136,47 @@ else() "conductor: SHA-256 backend = EVP (low-level API unavailable or forced)") endif() +if(WITH_CONDUCTOR_C_SHARED OR WITH_CONDUCTOR_GO) + if(NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") + message(FATAL_ERROR "Conductor C shared library currently supports Linux") + endif() + include(GNUInstallDirs) + add_library(mooncake_conductor_client SHARED src/client/conductor_c.cpp) + target_link_libraries(mooncake_conductor_client PRIVATE conductor_cpp_core) + set_target_properties( + mooncake_conductor_client + PROPERTIES VERSION 1.0.0 + SOVERSION 1 + INSTALL_RPATH "$ORIGIN" + LINK_DEPENDS + "${CMAKE_CURRENT_SOURCE_DIR}/src/client/conductor_c.map") + target_link_options( + mooncake_conductor_client + PRIVATE + "LINKER:--version-script=${CMAKE_CURRENT_SOURCE_DIR}/src/client/conductor_c.map" + ) + install(TARGETS mooncake_conductor_client + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}) + install(FILES include/conductor/client/conductor_c.h + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/conductor/client) +endif() + +if(WITH_CONDUCTOR_GO) + find_program(CONDUCTOR_GO_EXECUTABLE go) + if(NOT CONDUCTOR_GO_EXECUTABLE) + message(FATAL_ERROR "WITH_CONDUCTOR_GO=ON requires the Go compiler") + endif() + add_custom_target( + build_conductor_go ALL + COMMAND + ${CMAKE_COMMAND} -E env "GO=${CONDUCTOR_GO_EXECUTABLE}" bash + ${CMAKE_CURRENT_SOURCE_DIR}/go/build.sh ${CMAKE_CURRENT_BINARY_DIR} + ${CMAKE_CURRENT_BINARY_DIR}/mooncake-conductor-go-example + DEPENDS mooncake_conductor_client + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/go + VERBATIM) +endif() + if(BUILD_UNIT_TESTS) enable_testing() add_subdirectory(tests) diff --git a/mooncake-conductor/go/build.sh b/mooncake-conductor/go/build.sh new file mode 100644 index 00000000000..6d58ab19e73 --- /dev/null +++ b/mooncake-conductor/go/build.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# SPDX-License-Identifier: Apache-2.0 + +set -euo pipefail +if [ "$#" -ne 2 ]; then + echo "Usage: $0 CONDUCTOR_BUILD_DIR OUTPUT_BINARY" >&2 + exit 1 +fi +conductor_build=$(cd "$1" && pwd) +output_binary=$2 +script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +# Match Store's cgo build: provide native header and library paths explicitly. +export CGO_CFLAGS="-I${script_dir}/../include${CGO_CFLAGS:+ $CGO_CFLAGS}" +export CGO_LDFLAGS="-L${conductor_build} -lmooncake_conductor_client${CGO_LDFLAGS:+ $CGO_LDFLAGS}" +export CGO_ENABLED=1 +cd "$script_dir" +"${GO:-go}" build -o "$output_binary" ./examples/basic diff --git a/mooncake-conductor/go/examples/basic/main.go b/mooncake-conductor/go/examples/basic/main.go new file mode 100644 index 00000000000..538646af2af --- /dev/null +++ b/mooncake-conductor/go/examples/basic/main.go @@ -0,0 +1,42 @@ +// SPDX-License-Identifier: Apache-2.0 +package main + +import ( + "encoding/json" + "flag" + "fmt" + "log" + + conductor "github.com/kvcache-ai/Mooncake/mooncake-conductor/go/mooncakeconductor" +) + +func main() { + addr := flag.String("addr", "127.0.0.1:13334", "Conductor RPC address") + model := flag.String("model", "model", "registered model name") + block := flag.Int64("block-size", 16, "registered prefix block size") + flag.Parse() + if err := run(*addr, *model, *block); err != nil { + log.Fatal(err) + } +} + +func run(addr, model string, block int64) error { + client, err := conductor.New() + if err != nil { + return err + } + defer client.Close() + if err = client.Setup(conductor.ClientConfig{Address: addr}); err != nil { + return err + } + result, err := client.Query(conductor.QueryRequest{ModelName: model, BlockSize: block, TokenIDs: []int32{1, 2, 3}}) + if err != nil { + return err + } + data, err := json.Marshal(result) + if err != nil { + return err + } + fmt.Println(string(data)) + return nil +} diff --git a/mooncake-conductor/go/go.mod b/mooncake-conductor/go/go.mod new file mode 100644 index 00000000000..4608058350f --- /dev/null +++ b/mooncake-conductor/go/go.mod @@ -0,0 +1,3 @@ +module github.com/kvcache-ai/Mooncake/mooncake-conductor/go + +go 1.23 diff --git a/mooncake-conductor/go/mooncakeconductor/client.go b/mooncake-conductor/go/mooncakeconductor/client.go new file mode 100644 index 00000000000..ef0f8d0a444 --- /dev/null +++ b/mooncake-conductor/go/mooncakeconductor/client.go @@ -0,0 +1,145 @@ +// Copyright 2026 KVCache.AI +// SPDX-License-Identifier: Apache-2.0 +// Package mooncakeconductor provides a synchronous Conductor RPC client. +package mooncakeconductor + +import ( + "sync" + "time" +) + +// Client serializes operations on one RPC connection. Use separate clients for +// parallel requests. Do not copy a Client after first use. Close it explicitly. +type Client struct { + mu sync.Mutex + native *nativeClient +} + +func New() (*Client, error) { + n, err := newNative() + if err != nil { + return nil, err + } + return &Client{native: n}, nil +} + +func timeoutMillis(value, fallback time.Duration) (int64, error) { + // Native setup treats any negative timeout as disabled. + if value < 0 { + return -1, nil + } + // Rounded milliseconds must remain representable as native nanoseconds. + if value > time.Duration((1<<63-1)/int64(time.Millisecond))*time.Millisecond { + return 0, &Error{Op: "setup", Code: InvalidParams} + } + if value == 0 { + value = fallback + } + ms := int64(value / time.Millisecond) + if value%time.Millisecond != 0 { + ms++ + } + return ms, nil +} + +// Setup replaces any previous connection, including on failure. Zero timeouts +// use 1s/3s defaults; negative timeouts disable the timeout. After Close, +// Setup creates a fresh native client. +func (c *Client) Setup(config ClientConfig) error { + c.mu.Lock() + defer c.mu.Unlock() + connect, err := timeoutMillis(config.ConnectTimeout, time.Second) + var request int64 + if err == nil { + request, err = timeoutMillis(config.RequestTimeout, 3*time.Second) + } + if err != nil { + // Native Setup closes the old connection on valid Go input. Validation + // failures must also leave the previous connection unavailable. + if c.native != nil { + if closeErr := c.native.disconnect(); closeErr != nil { + return closeErr + } + } + return err + } + if c.native == nil { + c.native, err = newNative() + if err != nil { + return err + } + } + return c.native.setup(config.Address, connect, request) +} + +// Close releases client resources only; it does not unregister any publisher. +// It waits for an in-flight operation and is idempotent. +func (c *Client) Close() error { + c.mu.Lock() + defer c.mu.Unlock() + if c.native == nil { + return nil + } + err := c.native.close() + c.native = nil + return err +} + +// HealthCheck probes RPC reachability, not event progress or engine health. +func (c *Client) HealthCheck() (HealthStatus, error) { + c.mu.Lock() + defer c.mu.Unlock() + if c.native == nil { + return NotInitialized, nil + } + return c.native.health() +} + +func unavailable(op string) error { return &Error{Op: op, Code: ConductorUnavailable} } + +func (c *Client) Register(config ServiceConfig) (RegisterResult, error) { + c.mu.Lock() + defer c.mu.Unlock() + if c.native == nil { + return RegisterResult{}, unavailable("register") + } + return c.native.register(config) +} + +func (c *Client) Unregister(instanceID, tenantID string, dpRank int32) (UnregisterResult, error) { + c.mu.Lock() + defer c.mu.Unlock() + if c.native == nil { + return UnregisterResult{}, unavailable("unregister") + } + return c.native.unregister(instanceID, tenantID, dpRank) +} + +// Query sends raw tokens. Do not mutate TokenIDs during the call. RequestTimeout +// applies to the native RPC, not time waiting for another operation's mutex. +func (c *Client) Query(request QueryRequest) (QueryResult, error) { + c.mu.Lock() + defer c.mu.Unlock() + if c.native == nil { + return QueryResult{}, unavailable("query") + } + return c.native.query(request) +} + +func (c *Client) GetGlobalView() (GlobalView, error) { + c.mu.Lock() + defer c.mu.Unlock() + if c.native == nil { + return GlobalView{}, unavailable("get_global_view") + } + return c.native.global() +} + +func (c *Client) ListServices() ([]RegisteredService, error) { + c.mu.Lock() + defer c.mu.Unlock() + if c.native == nil { + return nil, unavailable("list_services") + } + return c.native.list() +} diff --git a/mooncake-conductor/go/mooncakeconductor/client_test.go b/mooncake-conductor/go/mooncakeconductor/client_test.go new file mode 100644 index 00000000000..2ff8e6ac84c --- /dev/null +++ b/mooncake-conductor/go/mooncakeconductor/client_test.go @@ -0,0 +1,151 @@ +// SPDX-License-Identifier: Apache-2.0 +package mooncakeconductor + +import ( + "encoding/json" + "errors" + "reflect" + "sync" + "testing" + "time" +) + +func TestTimeoutMillis(t *testing.T) { + for _, tc := range []struct { + input time.Duration + want int64 + invalid bool + }{ + {0, 1000, false}, {time.Nanosecond, 1, false}, {1500 * time.Microsecond, 2, false}, + {time.Second, 1000, false}, {-1, -1, false}, {time.Duration(-1 << 63), -1, false}, + {time.Duration(1<<63 - 1), 0, true}, + } { + got, err := timeoutMillis(tc.input, time.Second) + if got != tc.want || (err != nil) != tc.invalid { + t.Fatalf("%v: got %d, %v", tc.input, got, err) + } + } +} + +func TestTypedErrorAndQueryJSON(t *testing.T) { + err := nativeError("query", -901) + if !errors.Is(err, &Error{Code: RPCTimeout}) { + t.Fatal(err) + } + var native *Error + if !errors.As(err, &native) || native.Op != "query" { + t.Fatal(err) + } + if errors.Is(err, &Error{Code: RPCFail}) || nativeError("query", 0) != nil { + t.Fatal("incorrect error mapping") + } + if unknown := nativeError("query", -4321); !errors.As(unknown, &native) || native.Code != -4321 { + t.Fatal(unknown) + } + out := QueryResult{Instances: map[string]CacheHit{"engine": { + TierMatch: TierMatch{1, 2, 3, 4}, LongestMatched: 4, + DP: map[int64]int64{12: 1}, RankMatches: map[int64]TierMatch{12: {1, 2, 3, 4}}, + }}} + data, err := json.Marshal(out) + if err != nil { + t.Fatal(err) + } + var raw struct { + Instances map[string]map[string]json.RawMessage `json:"instances"` + } + if err := json.Unmarshal(data, &raw); err != nil { + t.Fatal(err) + } + keys := raw.Instances["engine"] + for _, key := range []string{"device", "cpu_local", "cpu_share", "disk", "longest_matched", "dp", "rank_matches"} { + if _, ok := keys[key]; !ok { + t.Fatalf("missing %s in %s", key, data) + } + } + if len(keys) != 7 { + t.Fatalf("extra aliases: %s", data) + } + var roundtrip QueryResult + if err := json.Unmarshal(data, &roundtrip); err != nil || !reflect.DeepEqual(out, roundtrip) { + t.Fatalf("%s: %v", data, err) + } +} + +func TestRegisteredServiceNestsRootDigest(t *testing.T) { + data, err := json.Marshal(RegisteredService{InstanceID: "engine", HashProfile: ResolvedHashProfile{RootDigest: "abc"}}) + if err != nil { + t.Fatal(err) + } + var raw struct { + RootDigest *string `json:"root_digest"` + HashProfile struct { + RootDigest string `json:"root_digest"` + } `json:"hash_profile"` + } + if err := json.Unmarshal(data, &raw); err != nil || raw.RootDigest != nil || raw.HashProfile.RootDigest != "abc" { + t.Fatalf("%s: %v", data, err) + } +} + +func TestLifecycleAndConcurrentClose(t *testing.T) { + c, err := New() + if err != nil { + t.Fatal(err) + } + defer c.Close() + if status, err := c.HealthCheck(); status != NotInitialized || err != nil { + t.Fatalf("%v %v", status, err) + } + if _, err := c.Query(QueryRequest{ModelName: "model", BlockSize: 16}); !errors.Is(err, &Error{Code: ConductorUnavailable}) { + t.Fatal(err) + } + if err := c.Setup(ClientConfig{Address: "invalid"}); !errors.Is(err, &Error{Code: InvalidParams}) { + t.Fatal(err) + } + if err := c.Setup(ClientConfig{Address: "invalid", RequestTimeout: time.Duration(1<<63 - 1)}); !errors.Is(err, &Error{Code: InvalidParams}) { + t.Fatal(err) + } + var wg sync.WaitGroup + for i := 0; i < 8; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for j := 0; j < 20; j++ { + c.HealthCheck() + if _, err := c.ListServices(); !errors.Is(err, &Error{Code: ConductorUnavailable}) { + t.Error(err) + } + if err := c.Close(); err != nil { + t.Error(err) + } + } + }() + } + wg.Wait() + if err := c.Setup(ClientConfig{Address: "invalid"}); !errors.Is(err, &Error{Code: InvalidParams}) { + t.Fatal(err) + } + if err := c.Close(); err != nil { + t.Fatal(err) + } +} + +func TestSharedABIInputValidation(t *testing.T) { + c, err := New() + if err != nil { + t.Fatal(err) + } + defer c.Close() + for _, op := range []func() error{ + func() error { return c.Setup(ClientConfig{Address: "host\x00:1234"}) }, + func() error { _, err := c.Query(QueryRequest{ModelName: "model\x00suffix"}); return err }, + func() error { _, err := c.Query(QueryRequest{CacheSalt: "salt\x00suffix"}); return err }, + func() error { _, err := c.Register(ServiceConfig{InstanceID: "instance\x00suffix"}); return err }, + func() error { _, err := c.Register(ServiceConfig{PublisherType: "unsupported"}); return err }, + func() error { _, err := c.Unregister("instance\x00suffix", "", 0); return err }, + } { + if err := op(); !errors.Is(err, &Error{Code: InvalidParams}) { + t.Fatalf("expected InvalidParams without truncating input, got %v", err) + } + } +} diff --git a/mooncake-conductor/go/mooncakeconductor/errors.go b/mooncake-conductor/go/mooncakeconductor/errors.go new file mode 100644 index 00000000000..ad011a2f994 --- /dev/null +++ b/mooncake-conductor/go/mooncakeconductor/errors.go @@ -0,0 +1,35 @@ +// Copyright 2026 KVCache.AI +// SPDX-License-Identifier: Apache-2.0 +package mooncakeconductor + +import "fmt" + +type ErrorCode int32 + +const ( + InternalError ErrorCode = -1 + InvalidParams ErrorCode = -600 + RPCFail ErrorCode = -900 + RPCTimeout ErrorCode = -901 + ConductorUnavailable ErrorCode = -2000 + ServiceNotFound ErrorCode = -2001 +) + +// Error retains the numeric native/RPC code. Use errors.As to inspect it. +type Error struct { + Op string + Code ErrorCode +} + +func (e *Error) Error() string { return fmt.Sprintf("mooncakeconductor: %s: error %d", e.Op, e.Code) } +func (e *Error) Is(target error) bool { + t, ok := target.(*Error) + return ok && t != nil && e.Code == t.Code +} + +func nativeError(op string, code int32) error { + if code == 0 { + return nil + } + return &Error{Op: op, Code: ErrorCode(code)} +} diff --git a/mooncake-conductor/go/mooncakeconductor/native.go b/mooncake-conductor/go/mooncakeconductor/native.go new file mode 100644 index 00000000000..aa14941bf76 --- /dev/null +++ b/mooncake-conductor/go/mooncakeconductor/native.go @@ -0,0 +1,232 @@ +// Copyright 2026 KVCache.AI +// SPDX-License-Identifier: Apache-2.0 +package mooncakeconductor + +/* +#include +#include +*/ +import "C" + +import ( + "runtime" + "strings" + "unsafe" +) + +type nativeClient struct { + handle C.mooncake_conductor_t + initialized bool +} + +func newNative() (*nativeClient, error) { + handle := C.mooncake_conductor_create() + if handle == nil { + return nil, &Error{Op: "create", Code: InternalError} + } + return &nativeClient{handle: handle}, nil +} + +// Pack NUL-terminated inputs into one C allocation. Reject embedded NULs so +// the shared C ABI cannot silently truncate Go strings. +func cStrings(op string, values ...string) ([]*C.char, func(), error) { + size := 0 + for _, s := range values { + if strings.IndexByte(s, 0) >= 0 { + return nil, nil, &Error{Op: op, Code: InvalidParams} + } + size += len(s) + 1 + } + data := C.malloc(C.size_t(size)) + views := make([]*C.char, len(values)) + offset := 0 + for i, s := range values { + ptr := unsafe.Add(data, offset) + bytes := unsafe.Slice((*byte)(ptr), len(s)+1) + copy(bytes, s) + bytes[len(s)] = 0 + views[i] = (*C.char)(ptr) + offset += len(s) + 1 + } + return views, func() { C.free(data) }, nil +} + +func (n *nativeClient) close() error { + C.mooncake_conductor_destroy(n.handle) + n.handle = nil + n.initialized = false + return nil +} + +func (n *nativeClient) disconnect() error { + C.mooncake_conductor_close(n.handle) + n.initialized = false + return nil +} + +func (n *nativeClient) setup(address string, connect, request int64) error { + n.initialized = false + v, free, err := cStrings("setup", address) + if err != nil { + n.disconnect() + return err + } + defer free() + err = nativeError("setup", int32(C.mooncake_conductor_setup(n.handle, v[0], C.int64_t(connect), C.int64_t(request)))) + n.initialized = err == nil + return err +} + +func (n *nativeClient) health() (HealthStatus, error) { + // Rust's status-only API remembers any prior successful setup. Go retains + // its existing contract: failed replacement setup means NotInitialized. + if !n.initialized { + return NotInitialized, nil + } + var status C.int + rc := C.mooncake_conductor_health_check_ex(n.handle, &status) + return HealthStatus(status), nativeError("health_check", int32(rc)) +} + +func publisherKind(value PublisherType) (C.int, error) { + switch value { + case "", PublisherVLLM: + return C.MOONCAKE_CONDUCTOR_PUBLISHER_VLLM, nil + case PublisherSGLang: + return C.MOONCAKE_CONDUCTOR_PUBLISHER_SGLANG, nil + case PublisherMooncake: + return C.MOONCAKE_CONDUCTOR_PUBLISHER_MOONCAKE, nil + default: + return 0, &Error{Op: "register", Code: InvalidParams} + } +} + +func publisherType(kind C.int) PublisherType { + switch kind { + case C.MOONCAKE_CONDUCTOR_PUBLISHER_VLLM: + return PublisherVLLM + case C.MOONCAKE_CONDUCTOR_PUBLISHER_SGLANG: + return PublisherSGLang + case C.MOONCAKE_CONDUCTOR_PUBLISHER_MOONCAKE: + return PublisherMooncake + default: + return "" + } +} + +func (n *nativeClient) register(cfg ServiceConfig) (RegisterResult, error) { + kind, err := publisherKind(cfg.PublisherType) + if err != nil { + return RegisterResult{}, err + } + v, free, err := cStrings("register", cfg.InstanceID, cfg.Endpoint, cfg.ReplayEndpoint, cfg.ModelName, + cfg.LoRAName, cfg.TenantID, cfg.HashProfile.Strategy, cfg.HashProfile.Algorithm, cfg.HashProfile.PythonHashSeed, cfg.HashProfile.IndexProjection) + if err != nil { + return RegisterResult{}, err + } + defer free() + c := C.mooncake_conductor_service_config_t{instance_id: v[0], endpoint: v[1], replay_endpoint: v[2], publisher_kind: kind, + model_name: v[3], lora_name: v[4], tenant_id: v[5], block_size: C.int64_t(cfg.BlockSize), dp_rank: C.int(cfg.DPRank), + hash_profile: C.mooncake_conductor_hash_profile_config_t{strategy: v[6], algorithm: v[7], python_hash_seed: v[8], index_projection: v[9]}} + if cfg.CacheGroup != nil { + c.has_cache_group = 1 + c.cache_group = C.int64_t(*cfg.CacheGroup) + } + var isNew C.int + if err := nativeError("register", int32(C.mooncake_conductor_register(n.handle, &c, &isNew))); err != nil { + return RegisterResult{}, err + } + return RegisterResult{InstanceID: cfg.InstanceID, IsNew: isNew != 0}, nil +} + +func (n *nativeClient) unregister(id, tenant string, rank int32) (UnregisterResult, error) { + v, free, err := cStrings("unregister", id, tenant) + if err != nil { + return UnregisterResult{}, err + } + defer free() + var key *C.char + if err := nativeError("unregister", int32(C.mooncake_conductor_unregister_ex(n.handle, v[0], v[1], C.int(rank), &key))); err != nil { + return UnregisterResult{}, err + } + defer C.mooncake_conductor_string_free(key) + return UnregisterResult{RemovedKey: C.GoString(key)}, nil +} + +func (n *nativeClient) query(req QueryRequest) (QueryResult, error) { + v, free, err := cStrings("query", req.ModelName, req.LoRAName, req.TenantID, req.CacheSalt, req.InstanceFilter) + if err != nil { + return QueryResult{}, err + } + defer free() + c := C.mooncake_conductor_query_request_t{model_name: v[0], lora_name: v[1], tenant_id: v[2], block_size: C.int64_t(req.BlockSize), cache_salt: v[3], instance_filter: v[4], token_count: C.size_t(len(req.TokenIDs))} + if len(req.TokenIDs) != 0 { + // The shared ABI embeds the borrowed token pointer in the request. + var pinned runtime.Pinner + pinned.Pin(&req.TokenIDs[0]) + defer pinned.Unpin() + c.token_ids = (*C.int32_t)(unsafe.Pointer(&req.TokenIDs[0])) + } + var result C.mooncake_conductor_query_result_t + rc := C.mooncake_conductor_query(n.handle, &c, &result) + runtime.KeepAlive(req.TokenIDs) + if err := nativeError("query", int32(rc)); err != nil { + return QueryResult{}, err + } + defer C.mooncake_conductor_query_result_free(&result) + out := QueryResult{Instances: make(map[string]CacheHit, int(result.hit_count))} + for _, hit := range unsafe.Slice(result.hits, int(result.hit_count)) { + h := CacheHit{TierMatch: TierMatch{Device: int64(hit.device), CPULocal: int64(hit.cpu_local), CPUShare: int64(hit.cpu_share), Disk: int64(hit.disk)}, LongestMatched: int64(hit.longest_matched), DP: make(map[int64]int64, int(hit.dp_count)), RankMatches: make(map[int64]TierMatch, int(hit.rank_match_count))} + for _, dp := range unsafe.Slice(hit.dp, int(hit.dp_count)) { + h.DP[int64(dp.rank)] = int64(dp.tokens) + } + for _, rank := range unsafe.Slice(hit.rank_matches, int(hit.rank_match_count)) { + h.RankMatches[int64(rank.rank)] = TierMatch{Device: int64(rank.device), CPULocal: int64(rank.cpu_local), CPUShare: int64(rank.cpu_share), Disk: int64(rank.disk)} + } + out.Instances[C.GoString(hit.instance_id)] = h + } + return out, nil +} + +func resolvedHashProfile(p C.mooncake_conductor_hash_profile_t) ResolvedHashProfile { + return ResolvedHashProfile{HashProfileConfig: HashProfileConfig{Strategy: C.GoString(p.strategy), Algorithm: C.GoString(p.algorithm), PythonHashSeed: C.GoString(p.python_hash_seed), IndexProjection: C.GoString(p.index_projection)}, RootDigest: C.GoString(p.root_digest)} +} + +func (n *nativeClient) list() ([]RegisteredService, error) { + var result C.mooncake_conductor_service_list_t + if err := nativeError("list_services", int32(C.mooncake_conductor_list_services(n.handle, &result))); err != nil { + return nil, err + } + defer C.mooncake_conductor_service_list_free(&result) + out := make([]RegisteredService, 0, int(result.service_count)) + for _, c := range unsafe.Slice(result.services, int(result.service_count)) { + s := RegisteredService{InstanceID: C.GoString(c.instance_id), Endpoint: C.GoString(c.endpoint), ReplayEndpoint: C.GoString(c.replay_endpoint), PublisherType: publisherType(c.publisher_kind), ModelName: C.GoString(c.model_name), LoRAName: C.GoString(c.lora_name), TenantID: C.GoString(c.tenant_id), BlockSize: int64(c.block_size), DPRank: int32(c.dp_rank), HashProfile: resolvedHashProfile(c.hash_profile)} + if c.has_cache_group != 0 { + group := int64(c.cache_group) + s.CacheGroup = &group + } + out = append(out, s) + } + return out, nil +} + +func (n *nativeClient) global() (GlobalView, error) { + var result C.mooncake_conductor_global_view_t + if err := nativeError("get_global_view", int32(C.mooncake_conductor_get_global_view(n.handle, &result))); err != nil { + return GlobalView{}, err + } + defer C.mooncake_conductor_global_view_free(&result) + out := GlobalView{ContextCount: int32(result.context_count), Contexts: make([]ContextView, 0, int(result.context_count))} + for _, c := range unsafe.Slice(result.contexts, int(result.context_count)) { + v := ContextView{ModelName: C.GoString(c.model_name), LoRAName: C.GoString(c.lora_name), TenantID: C.GoString(c.tenant_id), BlockSize: int64(c.block_size), PrefixCount: uint64(c.prefix_count), HashProfile: resolvedHashProfile(c.hash_profile), Instances: make(map[string][]int64, int(c.instance_count))} + for _, instance := range unsafe.Slice(c.instances, int(c.instance_count)) { + ranks := make([]int64, int(instance.rank_count)) + for i, r := range unsafe.Slice(instance.ranks, int(instance.rank_count)) { + ranks[i] = int64(r) + } + v.Instances[C.GoString(instance.instance_id)] = ranks + } + out.Contexts = append(out.Contexts, v) + } + return out, nil +} diff --git a/mooncake-conductor/go/mooncakeconductor/types.go b/mooncake-conductor/go/mooncakeconductor/types.go new file mode 100644 index 00000000000..01966ab8d6d --- /dev/null +++ b/mooncake-conductor/go/mooncakeconductor/types.go @@ -0,0 +1,120 @@ +// Copyright 2026 KVCache.AI +// SPDX-License-Identifier: Apache-2.0 +package mooncakeconductor + +import "time" + +type ClientConfig struct { + Address string + ConnectTimeout time.Duration + RequestTimeout time.Duration +} + +type PublisherType string + +const ( + PublisherVLLM PublisherType = "vLLM" + PublisherSGLang PublisherType = "SGLang" + PublisherMooncake PublisherType = "Mooncake" +) + +type HealthStatus int32 + +const ( + Healthy HealthStatus = iota + NotInitialized + Unreachable +) + +type HashProfileConfig struct { + Strategy string `json:"strategy"` + Algorithm string `json:"algorithm"` + PythonHashSeed string `json:"python_hash_seed"` + IndexProjection string `json:"index_projection"` +} + +type ResolvedHashProfile struct { + HashProfileConfig + RootDigest string `json:"root_digest"` +} + +type ServiceConfig struct { + InstanceID string `json:"instance_id"` + Endpoint string `json:"endpoint"` + ReplayEndpoint string `json:"replay_endpoint"` + PublisherType PublisherType `json:"publisher_type"` + ModelName string `json:"model_name"` + LoRAName string `json:"lora_name"` + TenantID string `json:"tenant_id"` + BlockSize int64 `json:"block_size"` + DPRank int32 `json:"dp_rank"` + CacheGroup *int64 `json:"cache_group"` + HashProfile HashProfileConfig `json:"hash_profile"` +} + +// RegisteredService is a service as reported by the conductor. Unlike +// ServiceConfig, its hash profile includes the server-resolved root digest. +type RegisteredService struct { + InstanceID string `json:"instance_id"` + Endpoint string `json:"endpoint"` + ReplayEndpoint string `json:"replay_endpoint"` + PublisherType PublisherType `json:"publisher_type"` + ModelName string `json:"model_name"` + LoRAName string `json:"lora_name"` + TenantID string `json:"tenant_id"` + BlockSize int64 `json:"block_size"` + DPRank int32 `json:"dp_rank"` + CacheGroup *int64 `json:"cache_group"` + HashProfile ResolvedHashProfile `json:"hash_profile"` +} + +type QueryRequest struct { + ModelName string + LoRAName string + TenantID string + BlockSize int64 + TokenIDs []int32 + CacheSalt string + InstanceFilter string +} + +// TierMatch holds cumulative continuous prefix lengths, not additive counts. +type TierMatch struct { + Device int64 `json:"device"` + CPULocal int64 `json:"cpu_local"` + CPUShare int64 `json:"cpu_share"` + Disk int64 `json:"disk"` +} + +type CacheHit struct { + TierMatch + LongestMatched int64 `json:"longest_matched"` + DP map[int64]int64 `json:"dp"` + RankMatches map[int64]TierMatch `json:"rank_matches"` +} + +type QueryResult struct { + Instances map[string]CacheHit `json:"instances"` +} + +type RegisterResult struct { + InstanceID string + IsNew bool +} + +type UnregisterResult struct{ RemovedKey string } + +type ContextView struct { + ModelName string `json:"model_name"` + LoRAName string `json:"lora_name"` + TenantID string `json:"tenant_id"` + BlockSize int64 `json:"block_size"` + PrefixCount uint64 `json:"prefix_count"` + HashProfile ResolvedHashProfile `json:"hash_profile"` + Instances map[string][]int64 `json:"instances"` +} + +type GlobalView struct { + ContextCount int32 `json:"context_count"` + Contexts []ContextView `json:"contexts"` +} diff --git a/mooncake-conductor/go/tests/client_e2e_test.go b/mooncake-conductor/go/tests/client_e2e_test.go new file mode 100644 index 00000000000..f2e21db5fac --- /dev/null +++ b/mooncake-conductor/go/tests/client_e2e_test.go @@ -0,0 +1,287 @@ +//go:build integration + +// SPDX-License-Identifier: Apache-2.0 +package tests + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "os" + "reflect" + "sync" + "testing" + "time" + + conductor "github.com/kvcache-ai/Mooncake/mooncake-conductor/go/mooncakeconductor" +) + +func control(t *testing.T, path string, body any, out any) { + t.Helper() + url := os.Getenv("CONDUCTOR_EVENT_HARNESS") + path + var resp *http.Response + var err error + httpClient := &http.Client{Timeout: 8 * time.Second} + if body == nil { + resp, err = httpClient.Get(url) + } else { + data, e := json.Marshal(body) + if e != nil { + t.Fatal(e) + } + resp, err = httpClient.Post(url, "application/json", bytes.NewReader(data)) + } + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + if resp.StatusCode != 200 { + data, _ := io.ReadAll(resp.Body) + t.Fatalf("harness %s: %d %s", path, resp.StatusCode, data) + } + if out != nil { + if err = json.NewDecoder(resp.Body).Decode(out); err != nil { + t.Fatal(err) + } + } +} + +func TestEventsToGoQuery(t *testing.T) { + if os.Getenv("CONDUCTOR_EVENT_HARNESS") == "" || os.Getenv("CONDUCTOR_RPC_ADDR") == "" { + t.Fatal("start event_harness.py and set CONDUCTOR_EVENT_HARNESS/CONDUCTOR_RPC_ADDR") + } + var fixtures struct { + Services []conductor.ServiceConfig `json:"services"` + SG []int32 `json:"sglang_tokens"` + VL []int32 `json:"vllm_tokens"` + } + control(t, "/", nil, &fixtures) + c, err := conductor.New() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { c.Close() }) + addr := os.Getenv("CONDUCTOR_RPC_ADDR") + if err = c.Setup(conductor.ClientConfig{Address: addr}); err != nil { + t.Fatal(err) + } + for _, svc := range fixtures.Services { + r, err := c.Register(svc) + if err != nil || !r.IsNew || r.InstanceID != svc.InstanceID { + t.Fatalf("register: %+v %v", r, err) + } + t.Cleanup(func() { c.Unregister(svc.InstanceID, svc.TenantID, svc.DPRank) }) + r, err = c.Register(svc) + if err != nil || r.IsNew { + t.Fatalf("idempotency: %+v %v", r, err) + } + } + conflict := fixtures.Services[0] + conflict.BlockSize = 8 + if _, err = c.Register(conflict); !errors.Is(err, &conductor.Error{Code: conductor.InvalidParams}) { + t.Fatal(err) + } + if status, err := c.HealthCheck(); status != conductor.Healthy || err != nil { + t.Fatalf("health %v %v", status, err) + } + svcs, err := c.ListServices() + if err != nil || len(svcs) != 4 { + t.Fatalf("services %v %v", svcs, err) + } + for _, s := range svcs { + if s.TenantID != "default" || len(s.HashProfile.RootDigest) != 64 && s.PublisherType == conductor.PublisherVLLM { + t.Fatalf("unresolved service %+v", s) + } + } + query := conductor.QueryRequest{ModelName: "go-sg", BlockSize: 4, TokenIDs: fixtures.SG} + for _, invalid := range []conductor.QueryRequest{{BlockSize: 4}, {ModelName: "go-sg"}} { + if _, e := c.Query(invalid); !errors.Is(e, &conductor.Error{Code: conductor.InvalidParams}) { + t.Fatal(e) + } + } + if missing, e := c.Query(conductor.QueryRequest{ModelName: "unregistered", BlockSize: 4}); e != nil || len(missing.Instances) != 0 { + t.Fatalf("missing context %+v %v", missing, e) + } + empty := query + empty.TokenIDs = nil + if result, e := c.Query(empty); e != nil { + t.Fatal(e) + } else { + for _, hit := range result.Instances { + if hit.LongestMatched != 0 { + t.Fatal(hit) + } + } + } + publish := func(name, action string) { + control(t, "/publish", map[string]string{"name": name, "action": action}, nil) + } + wait := func(req conductor.QueryRequest, want map[string]conductor.TierMatch) conductor.QueryResult { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for { + r, e := c.Query(req) + if e != nil { + t.Fatal(e) + } + ok := len(r.Instances) == len(want) + for id, m := range want { + h, exists := r.Instances[id] + ok = ok && exists && h.TierMatch == m && h.LongestMatched == m.Disk + } + if ok { + return r + } + if time.Now().After(deadline) { + t.Fatalf("want %v got %+v", want, r) + } + time.Sleep(20 * time.Millisecond) + } + } + for _, name := range []string{"sg0", "sg12", "vl0"} { + publish(name, "seed") + } + initial := conductor.TierMatch{Device: 4, CPULocal: 8, CPUShare: 8, Disk: 12} + wait(query, map[string]conductor.TierMatch{"sg0": initial, "sg12": initial}) + vlQuery := conductor.QueryRequest{ModelName: "go-vl", BlockSize: 4, TokenIDs: fixtures.VL} + wait(vlQuery, map[string]conductor.TierMatch{"vl0": {Device: 8, CPULocal: 8, CPUShare: 8, Disk: 8}}) + publish("pool", "seed") + shared := conductor.TierMatch{Device: 4, CPULocal: 8, CPUShare: 16, Disk: 16} + r := wait(query, map[string]conductor.TierMatch{"sg0": shared, "sg12": shared}) + for id, rank := range map[string]int64{"sg0": 0, "sg12": 12} { + h := r.Instances[id] + if !reflect.DeepEqual(h.DP, map[int64]int64{rank: 4}) || !reflect.DeepEqual(h.RankMatches, map[int64]conductor.TierMatch{rank: shared}) { + t.Fatalf("rank %+v", h) + } + } + var httpResult conductor.QueryResult + control(t, "/query", map[string]any{"model": "go-sg", "block_size": 4, "token_ids": fixtures.SG}, &httpResult) + if !reflect.DeepEqual(r, httpResult) { + t.Fatalf("Go %+v HTTP %+v", r, httpResult) + } + view, err := c.GetGlobalView() + if err != nil || view.ContextCount != 2 || len(view.Contexts) != 2 { + t.Fatalf("global %+v %v", view, err) + } + for _, v := range view.Contexts { + if v.ModelName == "go-sg" && (v.PrefixCount != 4 || !reflect.DeepEqual(v.Instances, map[string][]int64{"sg0": {0}, "sg12": {12}})) { + t.Fatalf("context %+v", v) + } + } + filtered := query + filtered.InstanceFilter = "sg12" + wait(filtered, map[string]conductor.TierMatch{"sg12": shared}) + publish("sg0", "remove") + withoutDevice := shared + withoutDevice.Device = 0 + wait(query, map[string]conductor.TierMatch{"sg0": withoutDevice, "sg12": shared}) + publish("sg0", "clear") + sharedOnly := conductor.TierMatch{CPUShare: 16, Disk: 16} + wait(query, map[string]conductor.TierMatch{"sg0": sharedOnly, "sg12": shared}) + publish("pool", "remove") + removed := shared + removed.CPUShare = 12 + wait(query, map[string]conductor.TierMatch{"sg0": {CPUShare: 12, Disk: 16}, "sg12": removed}) + publish("pool", "clear") + wait(query, map[string]conductor.TierMatch{"sg0": {}, "sg12": initial}) + publish("vl0", "remove") + wait(vlQuery, map[string]conductor.TierMatch{"vl0": {}}) + publish("vl0", "seed") + publish("vl0", "clear") + wait(vlQuery, map[string]conductor.TierMatch{"vl0": {}}) + // Go result ownership survives native result frees and connection close. + if err = c.Close(); err != nil { + t.Fatal(err) + } + if r.Instances["sg12"].RankMatches[12] != shared || len(view.Contexts) != 2 { + t.Fatal("borrowed output memory") + } + if err = c.Setup(conductor.ClientConfig{Address: addr}); err != nil { + t.Fatal(err) + } + for _, tc := range []struct { + config conductor.ClientConfig + code conductor.ErrorCode + }{ + {conductor.ClientConfig{Address: "invalid"}, conductor.InvalidParams}, + {conductor.ClientConfig{Address: addr + "\x00suffix"}, conductor.InvalidParams}, + {conductor.ClientConfig{Address: addr, ConnectTimeout: time.Duration(1<<63 - 1)}, conductor.InvalidParams}, + {conductor.ClientConfig{Address: addr, RequestTimeout: time.Duration(1<<63 - 1)}, conductor.InvalidParams}, + {conductor.ClientConfig{Address: "127.0.0.1:0"}, conductor.RPCFail}, + } { + if err = c.Setup(tc.config); !errors.Is(err, &conductor.Error{Code: tc.code}) { + t.Fatal(err) + } + if status, e := c.HealthCheck(); status != conductor.NotInitialized || e != nil { + t.Fatalf("failed setup health %v %v", status, e) + } + if _, e := c.ListServices(); !errors.Is(e, &conductor.Error{Code: conductor.ConductorUnavailable}) { + t.Fatal(e) + } + if err = c.Setup(conductor.ClientConfig{Address: addr}); err != nil { + t.Fatal(err) + } + } + // Negative timeouts disable the native timers instead of failing setup. + if err = c.Setup(conductor.ClientConfig{Address: addr, ConnectTimeout: -1, RequestTimeout: -1}); err != nil { + t.Fatal(err) + } + if status, e := c.HealthCheck(); status != conductor.Healthy || e != nil { + t.Fatalf("untimed health %v %v", status, e) + } + if err = c.Setup(conductor.ClientConfig{Address: addr}); err != nil { + t.Fatal(err) + } + for _, svc := range fixtures.Services { + u, e := c.Unregister(svc.InstanceID, svc.TenantID, svc.DPRank) + wantKey := fmt.Sprintf("%s|default|%d", svc.InstanceID, svc.DPRank) + if e != nil || u.RemovedKey != wantKey { + t.Fatalf("unregister %+v %v", u, e) + } + if _, e = c.Unregister(svc.InstanceID, svc.TenantID, svc.DPRank); !errors.Is(e, &conductor.Error{Code: conductor.ServiceNotFound}) { + t.Fatal(e) + } + } + if v, e := c.GetGlobalView(); e != nil { + t.Fatal(e) + } else { + // Context hash recipes remain after the last instance is unregistered. + for _, ctx := range v.Contexts { + if ctx.PrefixCount != 0 || len(ctx.Instances) != 0 { + t.Fatalf("cleanup %+v", ctx) + } + } + } + if s, e := c.ListServices(); e != nil || len(s) != 0 { + t.Fatalf("cleanup %+v %v", s, e) + } + // Exercise successful RPC calls racing with Close, not just nil handles. + var wg sync.WaitGroup + ready := make(chan struct{}, 6) + for i := 0; i < 6; i++ { + wg.Add(1) + go func() { + defer wg.Done() + if _, e := c.Query(query); e != nil { + t.Error(e) + } + ready <- struct{}{} + for j := 0; j < 20; j++ { + if _, e := c.Query(query); e != nil && !errors.Is(e, &conductor.Error{Code: conductor.ConductorUnavailable}) { + t.Error(e) + } + } + }() + } + for i := 0; i < 6; i++ { + <-ready + } + if err = c.Close(); err != nil { + t.Fatal(err) + } + wg.Wait() + fmt.Println("validated vLLM/SGLang/Mooncake events, four tiers, ranks, HTTP equivalence and client lifecycle") +} diff --git a/mooncake-conductor/go/tests/event_harness.py b/mooncake-conductor/go/tests/event_harness.py new file mode 100644 index 00000000000..1c840447772 --- /dev/null +++ b/mooncake-conductor/go/tests/event_harness.py @@ -0,0 +1,215 @@ +"""CPU-only event fixture publisher for the Go RPC integration tests. + +Run beside a Conductor configured with HTTP and RPC enabled and no services. +Requires pyzmq/msgpack; Go consumers do not require Python. +""" + +import argparse +import json +import time +from http.server import BaseHTTPRequestHandler, HTTPServer +from pathlib import Path +from urllib.request import Request, urlopen + +import msgpack +import zmq + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--port", type=int, required=True) + parser.add_argument("--http-port", type=int, required=True) + args = parser.parse_args() + fixtures = Path(__file__).resolve().parents[2] / "tests/fixtures" + sg = json.loads((fixtures / "sglang_map_event_vectors.json").read_text())[ + "integration" + ] + vl = json.loads((fixtures / "hash_golden_vectors_sha256.json").read_text()) + context = zmq.Context() + sockets, sequences, subscribed = {}, {}, set() + configs = [] + sg_profile = dict( + strategy="sglang", + algorithm="sha256_raw", + python_hash_seed="", + index_projection="first64_be", + ) + for name, publisher, model, rank, profile in [ + ("sg0", "SGLang", "go-sg", 0, sg_profile), + ("sg12", "SGLang", "go-sg", 12, sg_profile), + ("pool", "Mooncake", "go-sg", 0, sg_profile), + ( + "vl0", + "vLLM", + "go-vl", + 0, + {k: v for k, v in vl["profile"].items() if k != "root_digest"}, + ), + ]: + socket = context.socket(zmq.XPUB) + socket.setsockopt(zmq.LINGER, 0) + port = socket.bind_to_random_port("tcp://127.0.0.1") + sockets[name], sequences[name] = socket, 0 + configs.append( + dict( + instance_id=name, + endpoint=f"tcp://127.0.0.1:{port}", + publisher_type=publisher, + model_name=model, + block_size=4, + dp_rank=rank, + hash_profile=profile, + ) + ) + + def publish(name, payload): + socket = sockets[name] + if name not in subscribed: + deadline = time.monotonic() + 5 + while time.monotonic() < deadline: + if socket.poll(100) and socket.recv().startswith(b"\x01"): + subscribed.add(name) + break + else: + raise RuntimeError(f"No subscriber for {name}") + socket.send_multipart([b"", sequences[name].to_bytes(8, "big"), payload]) + sequences[name] += 1 + + def engine(name, action): + if name == "vl0": + case = vl["cases"][0] + hashes = [int(h["projected_decimal"]) for h in case["expected"]] + if action == "seed": + events = [ + dict( + type="BlockStored", + block_hashes=hashes, + parent_block_hash=None, + token_ids=case["token_ids"], + block_size=4, + lora_id=None, + lora_name=None, + medium="GPU", + ) + ] + elif action == "remove": + events = [ + dict(type="BlockRemoved", block_hashes=[hashes[0]], medium="GPU") + ] + else: + events = [dict(type="AllBlocksCleared")] + publish(name, msgpack.packb([time.time(), events, 0])) + else: + rank = 12 if name == "sg12" else 0 + payloads = ( + [p["payload_hex"] for p in sg["tier_publishes"]] + if action == "seed" + else [ + sg["remove_first_block_hex"] + if action == "remove" + else sg["clear_all_hex"] + ] + ) + for payload in payloads: + batch = msgpack.unpackb(bytes.fromhex(payload), raw=False) + batch[2] = rank + publish(name, msgpack.packb(batch)) + + def pool(action): + timestamp = int(time.time() * 1000) + common = dict( + timestamp=timestamp, + model_name="go-sg", + block_size=4, + additional_salt=None, + lora_name=None, + tenant_id="default", + backend_id="pool", + dp_rank=0, + ) + events = [] + if action == "seed": + for medium in ["CPU", "DISK"]: + for digest in sg["upstream_hex_digests"]: + events.append( + dict( + common, + event_type="stored", + event_id=len(events), + medium=medium, + group_id=None, + seq_hashes=[], + base_block_idx=None, + object_key=f"go_{digest}_k", + parent_hash=None, + token_ids=None, + ) + ) + elif action == "remove": + events.append( + dict( + common, + event_type="removed", + event_id=0, + medium="CPU", + group_id=None, + seq_hashes=[], + base_block_idx=None, + object_key=f"go_{sg['upstream_hex_digests'][-1]}_k", + ) + ) + else: + events.append(dict(common, event_type="cleared", event_id=0, medium=None)) + publish("pool", msgpack.packb([timestamp, events, 0])) + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *_): + pass + + def respond(self, value, status=200): + body = json.dumps(value).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + self.respond( + dict( + services=configs, + sglang_tokens=sg["token_ids"], + vllm_tokens=vl["cases"][0]["token_ids"], + ) + ) + + def do_POST(self): + try: + body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) + if self.path == "/query": + request = Request( + f"http://127.0.0.1:{args.http_port}/query", + data=msgpack.packb(body), + headers={"Content-Type": "application/msgpack"}, + ) + with urlopen(request, timeout=5) as response: + self.respond(msgpack.unpackb(response.read(), raw=False)) + else: + name, action = body["name"], body["action"] + if action not in {"seed", "remove", "clear"}: + raise ValueError("invalid action") + pool(action) if name == "pool" else engine(name, action) + self.respond({"ok": True}) + except Exception as exc: + self.respond({"error": str(exc)}, 500) + + try: + HTTPServer(("127.0.0.1", args.port), Handler).serve_forever() + finally: + for socket in sockets.values(): + socket.close() + context.term() + + +if __name__ == "__main__": + main() diff --git a/mooncake-conductor/include/conductor/client/conductor_c.h b/mooncake-conductor/include/conductor/client/conductor_c.h index fb86173dc29..3b7f9288754 100644 --- a/mooncake-conductor/include/conductor/client/conductor_c.h +++ b/mooncake-conductor/include/conductor/client/conductor_c.h @@ -1,5 +1,5 @@ -// C ABI over ConductorClient, consumed by the Rust bindings in -// mooncake-conductor/rust. Mirrors the Python _conductor module: the same +// C ABI over ConductorClient, consumed by the Rust and Go bindings. +// Mirrors the Python _conductor module: the same // operations, defaults, and numeric return codes. #ifndef MOONCAKE_CONDUCTOR_C_H @@ -236,7 +236,11 @@ mooncake_conductor_t mooncake_conductor_create(void); /* Closes the connection and releases the handle; NULL is a no-op. */ void mooncake_conductor_destroy(mooncake_conductor_t conductor); -/* Connects to "host:port". Setup may be called again after close. */ +/* + * Connects to "host:port". Setup may be called again after close. A negative + * timeout disables that timeout; 0 or a value above INT64_MAX / 1000000 + * returns MOONCAKE_CONDUCTOR_INVALID_PARAMS. + */ int mooncake_conductor_setup(mooncake_conductor_t conductor, const char *conductor_addr, int64_t connect_timeout_ms, @@ -252,6 +256,11 @@ void mooncake_conductor_close(mooncake_conductor_t conductor); */ int mooncake_conductor_health_check(mooncake_conductor_t conductor); +// Like health_check, with the status in *status and the original RPC error +// returned separately. Existing health_check keeps its status-only contract. +int mooncake_conductor_health_check_ex(mooncake_conductor_t conductor, + int *status); + // --------------------------------------------------------------------------- // Operations // --------------------------------------------------------------------------- @@ -276,6 +285,14 @@ int mooncake_conductor_unregister(mooncake_conductor_t conductor, const char *instance_id, const char *tenant_id, int dp_rank); +// Like unregister, also returning the server's removed service key. The output +// is NULL on failure; release a successful key with string_free. +int mooncake_conductor_unregister_ex(mooncake_conductor_t conductor, + const char *instance_id, + const char *tenant_id, int dp_rank, + char **removed_key); +void mooncake_conductor_string_free(char *value); + int mooncake_conductor_get_global_view(mooncake_conductor_t conductor, mooncake_conductor_global_view_t *view); diff --git a/mooncake-conductor/include/conductor/client/conductor_client.h b/mooncake-conductor/include/conductor/client/conductor_client.h index 5b2d5ef4860..9a4d25a2f74 100644 --- a/mooncake-conductor/include/conductor/client/conductor_client.h +++ b/mooncake-conductor/include/conductor/client/conductor_client.h @@ -13,6 +13,8 @@ namespace mooncake::conductor { struct ConductorClientConfig { std::string conductor_addr; // RPC server address, "host:port" + // Negative disables the timeout. Setup rejects 0 and values above + // INT64_MAX / 1000000 with INVALID_PARAMS. int64_t connect_timeout_ms = 1000; int64_t request_timeout_ms = 3000; }; @@ -32,7 +34,7 @@ class ConductorClient { // Replaces the previous connection; failure leaves the client unconnected. tl::expected Setup(const ConductorClientConfig& config); - void Close(); // idempotent; Setup() may be called again afterwards + void Close(); // drains socket cleanup; idempotent; Setup may reconnect bool HealthCheck(); // healthy if one ListServices call succeeds tl::expected Query(const QueryRequest& request); diff --git a/mooncake-conductor/rust/src/client.rs b/mooncake-conductor/rust/src/client.rs index 0cacfafaf51..8d49dde43a5 100644 --- a/mooncake-conductor/rust/src/client.rs +++ b/mooncake-conductor/rust/src/client.rs @@ -93,8 +93,10 @@ unsafe fn hash_profile(raw: &ffi::mooncake_conductor_hash_profile_t) -> HashProf } } +/// Round up so a nonzero duration never becomes the rejected 0 ms; values +/// past `i64::MAX` saturate and setup rejects them as out of range. fn millis(duration: Duration) -> i64 { - i64::try_from(duration.as_millis()).unwrap_or(i64::MAX) + i64::try_from(duration.as_nanos().div_ceil(1_000_000)).unwrap_or(i64::MAX) } impl ConductorClient { @@ -337,7 +339,10 @@ mod tests { } #[test] - fn millis_saturates() { + fn millis_rounds_up_and_saturates() { + assert_eq!(millis(Duration::ZERO), 0); + assert_eq!(millis(Duration::from_nanos(1)), 1); + assert_eq!(millis(Duration::from_micros(1500)), 2); assert_eq!(millis(Duration::from_millis(1500)), 1500); assert_eq!(millis(Duration::MAX), i64::MAX); } diff --git a/mooncake-conductor/rust/src/types.rs b/mooncake-conductor/rust/src/types.rs index 1dfb8e0366a..67991c808b9 100644 --- a/mooncake-conductor/rust/src/types.rs +++ b/mooncake-conductor/rust/src/types.rs @@ -23,7 +23,10 @@ use std::time::Duration; pub struct ClientConfig { /// RPC server address, `"host:port"`. pub conductor_addr: String, + /// Rounded up to whole milliseconds. `setup` returns `InvalidParams` for + /// zero or for more than `i64::MAX / 1_000_000` ms. pub connect_timeout: Duration, + /// Same rules as `connect_timeout`. pub request_timeout: Duration, } diff --git a/mooncake-conductor/src/client/conductor_c.cpp b/mooncake-conductor/src/client/conductor_c.cpp index fe41a787b10..f4381fa91a9 100644 --- a/mooncake-conductor/src/client/conductor_c.cpp +++ b/mooncake-conductor/src/client/conductor_c.cpp @@ -247,17 +247,28 @@ void mooncake_conductor_close(mooncake_conductor_t conductor) { } int mooncake_conductor_health_check(mooncake_conductor_t conductor) { - if (!conductor) return MOONCAKE_CONDUCTOR_HEALTH_NOT_INITIALIZED; + int status = MOONCAKE_CONDUCTOR_HEALTH_NOT_INITIALIZED; + mooncake_conductor_health_check_ex(conductor, &status); + return status; +} + +int mooncake_conductor_health_check_ex(mooncake_conductor_t conductor, + int *status) { + if (!status) return MOONCAKE_CONDUCTOR_INVALID_PARAMS; + *status = MOONCAKE_CONDUCTOR_HEALTH_NOT_INITIALIZED; + if (!conductor) return MOONCAKE_CONDUCTOR_OK; auto *handle = as_handle(conductor); if (!handle->setup_called.load()) { - return MOONCAKE_CONDUCTOR_HEALTH_NOT_INITIALIZED; + return MOONCAKE_CONDUCTOR_OK; } + *status = MOONCAKE_CONDUCTOR_HEALTH_UNREACHABLE; try { - return handle->client.HealthCheck() - ? MOONCAKE_CONDUCTOR_HEALTH_OK - : MOONCAKE_CONDUCTOR_HEALTH_UNREACHABLE; + auto result = handle->client.ListServices(); + if (!result) return to_rc(result.error()); + *status = MOONCAKE_CONDUCTOR_HEALTH_OK; + return MOONCAKE_CONDUCTOR_OK; } catch (...) { - return MOONCAKE_CONDUCTOR_HEALTH_UNREACHABLE; + return MOONCAKE_CONDUCTOR_INTERNAL_ERROR; } } @@ -271,7 +282,8 @@ int mooncake_conductor_query(mooncake_conductor_t conductor, if (!result) return MOONCAKE_CONDUCTOR_INVALID_PARAMS; *result = {}; if (!conductor || !request || - (!request->token_ids && request->token_count > 0)) { + (!request->token_ids && request->token_count > 0) || + request->token_count > std::vector().max_size()) { return MOONCAKE_CONDUCTOR_INVALID_PARAMS; } try { @@ -353,17 +365,30 @@ int mooncake_conductor_register( int mooncake_conductor_unregister(mooncake_conductor_t conductor, const char *instance_id, const char *tenant_id, int dp_rank) { + return mooncake_conductor_unregister_ex(conductor, instance_id, tenant_id, + dp_rank, nullptr); +} + +int mooncake_conductor_unregister_ex(mooncake_conductor_t conductor, + const char *instance_id, + const char *tenant_id, int dp_rank, + char **removed_key) { + if (removed_key) *removed_key = nullptr; if (!conductor) return MOONCAKE_CONDUCTOR_INVALID_PARAMS; try { auto rpc = as_handle(conductor)->client.Unregister( to_string_or_empty(instance_id), to_string_or_empty(tenant_id), dp_rank); - return rpc ? MOONCAKE_CONDUCTOR_OK : to_rc(rpc.error()); + if (!rpc) return to_rc(rpc.error()); + if (removed_key) *removed_key = dup_string(rpc->removed_key); + return MOONCAKE_CONDUCTOR_OK; } catch (...) { return MOONCAKE_CONDUCTOR_INTERNAL_ERROR; } } +void mooncake_conductor_string_free(char *value) { std::free(value); } + int mooncake_conductor_get_global_view(mooncake_conductor_t conductor, mooncake_conductor_global_view_t *view) { if (!view) return MOONCAKE_CONDUCTOR_INVALID_PARAMS; diff --git a/mooncake-conductor/src/client/conductor_c.map b/mooncake-conductor/src/client/conductor_c.map new file mode 100644 index 00000000000..47a4ab54c40 --- /dev/null +++ b/mooncake-conductor/src/client/conductor_c.map @@ -0,0 +1,4 @@ +MOONCAKE_CONDUCTOR_1 { + global: mooncake_conductor_*; + local: *; +}; diff --git a/mooncake-conductor/src/client/conductor_client.cpp b/mooncake-conductor/src/client/conductor_client.cpp index 239b98771c2..0877cf15eec 100644 --- a/mooncake-conductor/src/client/conductor_client.cpp +++ b/mooncake-conductor/src/client/conductor_client.cpp @@ -7,7 +7,9 @@ #include #include +#include #include +#include #include #include @@ -20,19 +22,53 @@ struct ConductorClient::Impl { std::mutex mu; // serializes calls; see header's thread-safety note int64_t request_timeout_ms = 3000; bool connected = false; + bool cleanup_drained = false; + + // Caller holds mu. Only a new connection attempt invalidates this state. + void Close() { + connected = false; + if (cleanup_drained) return; + // ylt close() dispatches socket cleanup asynchronously. Complete it + // before short-lived callers release the client and exit. + client.close(); + auto executor = client.get_executor().get_asio_executor(); + if (!executor.running_in_this_thread()) { + async_simple::coro::syncAwait(coro_io::post([] {}, executor)); + } + cleanup_drained = true; + } }; ConductorClient::ConductorClient() : impl_(std::make_unique()) {} -ConductorClient::~ConductorClient() { Close(); } +ConductorClient::~ConductorClient() { + try { + Close(); + } catch (...) { + // Destruction must not propagate allocation/executor failures. The + // native RPC member still performs its own socket cleanup. + } +} tl::expected ConductorClient::Setup( const ConductorClientConfig& config) { std::lock_guard lock(impl_->mu); // Every setup attempt replaces the previous connection, even if the new // address is invalid or the connection fails. - impl_->connected = false; - impl_->client.close(); - impl_->request_timeout_ms = config.request_timeout_ms; + impl_->Close(); + // A negative timeout disables the ylt timer. Zero would expire at once, + // and larger values overflow ylt's nanosecond conversion. + constexpr int64_t max_timeout_ms = + std::numeric_limits::max() / 1000000; + if (config.connect_timeout_ms == 0 || config.request_timeout_ms == 0 || + config.connect_timeout_ms > max_timeout_ms || + config.request_timeout_ms > max_timeout_ms) { + return tl::make_unexpected(ErrorCode::INVALID_PARAMS); + } + // Clamp negatives to -1 so the nanosecond conversion cannot overflow. + const int64_t connect_timeout_ms = + std::max(config.connect_timeout_ms, -1); + impl_->request_timeout_ms = + std::max(config.request_timeout_ms, -1); // Split "host:port" for coro_rpc_client::connect(host, port). const auto colon = config.conductor_addr.rfind(':'); if (colon == std::string::npos) { @@ -40,10 +76,11 @@ tl::expected ConductorClient::Setup( } const std::string host = config.conductor_addr.substr(0, colon); const std::string port = config.conductor_addr.substr(colon + 1); + impl_->cleanup_drained = false; auto ec = async_simple::coro::syncAwait(impl_->client.connect( - host, port, std::chrono::milliseconds(config.connect_timeout_ms))); + host, port, std::chrono::milliseconds(connect_timeout_ms))); if (ec) { - impl_->client.close(); + impl_->Close(); return tl::make_unexpected(ErrorCode::RPC_FAIL); } impl_->connected = true; @@ -52,11 +89,7 @@ tl::expected ConductorClient::Setup( void ConductorClient::Close() { std::lock_guard lock(impl_->mu); - impl_->connected = false; - // ylt 0.5.7 client.close() uses close_socket_async: a CAS keeps it - // idempotent, the socket closes asynchronously without blocking, and - // connect_impl resets has_closed_, so Setup() after Close() reconnects. - impl_->client.close(); + impl_->Close(); } bool ConductorClient::HealthCheck() { diff --git a/mooncake-conductor/tests/CMakeLists.txt b/mooncake-conductor/tests/CMakeLists.txt index 899c84a3f84..3f9ff4efbb4 100644 --- a/mooncake-conductor/tests/CMakeLists.txt +++ b/mooncake-conductor/tests/CMakeLists.txt @@ -23,7 +23,8 @@ add_executable( conductor_service_test.cpp wire_types_test.cpp client_server_e2e_test.cpp - conductor_c_test.cpp) + conductor_c_test.cpp + conductor_c_extensions_test.cpp) target_link_libraries(conductor_test PRIVATE conductor_cpp_core ${CONDUCTOR_GTEST_LIBS}) @@ -34,3 +35,17 @@ target_compile_definitions( PRIVATE CONDUCTOR_TEST_FIXTURE_DIR="${CMAKE_CURRENT_SOURCE_DIR}/fixtures") add_test(NAME conductor_test COMMAND conductor_test) + +if(TARGET mooncake_conductor_client) + enable_language(C) + add_executable(conductor_c_header_test conductor_c_header_test.c) + target_include_directories(conductor_c_header_test PRIVATE ../include) + target_link_libraries(conductor_c_header_test + PRIVATE mooncake_conductor_client) + add_test(NAME conductor_c_header_test COMMAND conductor_c_header_test) + add_test( + NAME conductor_c_lifecycle_test + COMMAND ${CMAKE_COMMAND} -DPROGRAM=$ + -P ${CMAKE_CURRENT_SOURCE_DIR}/repeat_client_lifecycle.cmake) + set_tests_properties(conductor_c_lifecycle_test PROPERTIES TIMEOUT 30) +endif() diff --git a/mooncake-conductor/tests/conductor_c_extensions_test.cpp b/mooncake-conductor/tests/conductor_c_extensions_test.cpp new file mode 100644 index 00000000000..115ae94119c --- /dev/null +++ b/mooncake-conductor/tests/conductor_c_extensions_test.cpp @@ -0,0 +1,135 @@ +// SPDX-License-Identifier: Apache-2.0 +#include + +#include +#include +#include +#include +#include + +#include "conductor/client/conductor_c.h" +#include "conductor/kvevent/event_manager.h" +#include "prefix_indexer_test_peer.h" + +namespace { +TEST(ConductorCExtensions, HealthErrorsAndServerUnregisterKey) { + int status = -1; + EXPECT_EQ(mooncake_conductor_health_check_ex(nullptr, &status), 0); + EXPECT_EQ(status, MOONCAKE_CONDUCTOR_HEALTH_NOT_INITIALIZED); + EXPECT_EQ(mooncake_conductor_health_check_ex(nullptr, nullptr), + MOONCAKE_CONDUCTOR_INVALID_PARAMS); + char* removed_key = reinterpret_cast(1); + EXPECT_EQ( + mooncake_conductor_unregister_ex(nullptr, "i", "", 0, &removed_key), + MOONCAKE_CONDUCTOR_INVALID_PARAMS); + EXPECT_EQ(removed_key, nullptr); + mooncake_conductor_string_free(nullptr); + + mooncake::conductor::kvevent::EventManager manager({}, 0, 19336); + ASSERT_TRUE(manager.StartRPCServer()); + manager.Start(); + std::unique_ptr client( + mooncake_conductor_create(), mooncake_conductor_destroy); + ASSERT_NE(client.get(), nullptr); + mooncake_conductor_query_request_t oversized{}; + int32_t token = 1; + oversized.token_ids = &token; + oversized.token_count = SIZE_MAX; + mooncake_conductor_query_result_t empty{}; + EXPECT_EQ(mooncake_conductor_query(client.get(), &oversized, &empty), + MOONCAKE_CONDUCTOR_INVALID_PARAMS); + EXPECT_EQ(empty.hits, nullptr); + int rc = -1; + for (int i = 0; i < 40 && rc != 0; ++i) { + rc = mooncake_conductor_setup(client.get(), "127.0.0.1:19336", 1000, + 3000); + if (rc) std::this_thread::sleep_for(std::chrono::milliseconds(25)); + } + ASSERT_EQ(rc, 0); + EXPECT_EQ(mooncake_conductor_health_check_ex(client.get(), &status), 0); + EXPECT_EQ(status, MOONCAKE_CONDUCTOR_HEALTH_OK); + + mooncake_conductor_service_config_t cfg{}; + cfg.instance_id = "c-go-shared"; + cfg.endpoint = "tcp://127.0.0.1:29336"; + cfg.model_name = "extensions"; + cfg.block_size = 4; + cfg.dp_rank = 12; + cfg.hash_profile = {"sglang", "sha256_raw", "", "first64_be"}; + cfg.publisher_kind = MOONCAKE_CONDUCTOR_PUBLISHER_SGLANG; + ASSERT_EQ(mooncake_conductor_register(client.get(), &cfg, nullptr), 0); + ASSERT_EQ( + mooncake_conductor_setup(client.get(), "127.0.0.1:19336", 1000, 100), + 0); + { + mooncake::conductor::prefixindex::ContextKey context{ + "default", cfg.model_name, "", cfg.block_size}; + auto state_lock = + mooncake::conductor::prefixindex::PrefixCacheTableTestPeer:: + LockContextState(*manager.GetIndexer(), context); + ASSERT_TRUE(state_lock.owns_lock()); + int32_t tokens[] = {1, 2, 3, 4}; + mooncake_conductor_query_request_t request{}; + request.model_name = cfg.model_name; + request.block_size = cfg.block_size; + request.token_ids = tokens; + request.token_count = 4; + mooncake_conductor_query_result_t result{}; + EXPECT_EQ(mooncake_conductor_query(client.get(), &request, &result), + MOONCAKE_CONDUCTOR_RPC_TIMEOUT); + EXPECT_EQ(result.hits, nullptr); + EXPECT_EQ(result.hit_count, 0u); + } + ASSERT_EQ( + mooncake_conductor_setup(client.get(), "127.0.0.1:19336", 1000, 3000), + 0); + ASSERT_EQ(mooncake_conductor_unregister_ex(client.get(), cfg.instance_id, + "", cfg.dp_rank, &removed_key), + 0); + std::unique_ptr key( + removed_key, mooncake_conductor_string_free); + EXPECT_STREQ(key.get(), "c-go-shared|default|12"); + EXPECT_EQ(mooncake_conductor_unregister_ex(client.get(), cfg.instance_id, + "", cfg.dp_rank, &removed_key), + MOONCAKE_CONDUCTOR_SERVICE_NOT_FOUND); + EXPECT_EQ(removed_key, nullptr); + + // Existing Rust status-only semantics remain unchanged after a Close or + // failed replacement setup; detailed callers also retain the native code. + // A zero timeout would expire at once, so setup rejects it. + EXPECT_EQ( + mooncake_conductor_setup(client.get(), "127.0.0.1:19336", 0, 3000), + MOONCAKE_CONDUCTOR_INVALID_PARAMS); + EXPECT_EQ(mooncake_conductor_health_check(client.get()), + MOONCAKE_CONDUCTOR_HEALTH_UNREACHABLE); + EXPECT_EQ(mooncake_conductor_health_check_ex(client.get(), &status), + MOONCAKE_CONDUCTOR_UNAVAILABLE); + EXPECT_EQ(status, MOONCAKE_CONDUCTOR_HEALTH_UNREACHABLE); + constexpr int64_t too_large = + std::numeric_limits::max() / 1000000 + 1; + EXPECT_EQ(mooncake_conductor_setup(client.get(), "127.0.0.1:19336", + too_large, 3000), + MOONCAKE_CONDUCTOR_INVALID_PARAMS); + EXPECT_EQ(mooncake_conductor_setup(client.get(), "127.0.0.1:19336", 1000, + too_large), + MOONCAKE_CONDUCTOR_INVALID_PARAMS); + // Negative timeouts disable the timers, including values far below -1. + ASSERT_EQ(mooncake_conductor_setup(client.get(), "127.0.0.1:19336", -1, -1), + 0); + EXPECT_EQ(mooncake_conductor_health_check_ex(client.get(), &status), 0); + EXPECT_EQ(status, MOONCAKE_CONDUCTOR_HEALTH_OK); + ASSERT_EQ(mooncake_conductor_setup(client.get(), "127.0.0.1:19336", + std::numeric_limits::min(), + std::numeric_limits::min()), + 0); + EXPECT_EQ(mooncake_conductor_health_check_ex(client.get(), &status), 0); + EXPECT_EQ(status, MOONCAKE_CONDUCTOR_HEALTH_OK); + ASSERT_EQ( + mooncake_conductor_setup(client.get(), "127.0.0.1:19336", 1000, 3000), + 0); + manager.Stop(); + EXPECT_NE(mooncake_conductor_health_check_ex(client.get(), &status), 0); + EXPECT_EQ(status, MOONCAKE_CONDUCTOR_HEALTH_UNREACHABLE); + EXPECT_EQ(mooncake_conductor_health_check(client.get()), status); +} +} // namespace diff --git a/mooncake-conductor/tests/conductor_c_header_test.c b/mooncake-conductor/tests/conductor_c_header_test.c new file mode 100644 index 00000000000..84e1d27c976 --- /dev/null +++ b/mooncake-conductor/tests/conductor_c_header_test.c @@ -0,0 +1,14 @@ +// SPDX-License-Identifier: Apache-2.0 +#include "conductor/client/conductor_c.h" + +int main(void) { + mooncake_conductor_t client = mooncake_conductor_create(); + int status = -1; + if (!client) return 1; + if (mooncake_conductor_health_check_ex(client, &status) != 0 || status != 1) + return 3; + mooncake_conductor_close(client); + mooncake_conductor_close(client); + mooncake_conductor_destroy(client); + return 0; +} diff --git a/mooncake-conductor/tests/repeat_client_lifecycle.cmake b/mooncake-conductor/tests/repeat_client_lifecycle.cmake new file mode 100644 index 00000000000..21706ad2238 --- /dev/null +++ b/mooncake-conductor/tests/repeat_client_lifecycle.cmake @@ -0,0 +1,11 @@ +# SPDX-License-Identifier: Apache-2.0 Exercise process exit, where pending +# native cleanup can race global teardown. +foreach(attempt RANGE 1 100) + execute_process( + COMMAND "${PROGRAM}" + RESULT_VARIABLE status + TIMEOUT 5) + if(NOT status STREQUAL "0") + message(FATAL_ERROR "Client lifecycle process ${attempt} failed: ${status}") + endif() +endforeach() diff --git a/mooncake-store/src/real_client.cpp b/mooncake-store/src/real_client.cpp index 8c61f72635a..f590bf4a25e 100644 --- a/mooncake-store/src/real_client.cpp +++ b/mooncake-store/src/real_client.cpp @@ -1517,7 +1517,10 @@ tl::expected RealClient::setup_internal( << "sunrise_link protocol requires USE_SUNRISE build"; return tl::unexpected(ErrorCode::INVALID_PARAMS); #endif - } else if (this->protocol == "ub") { + } else if (this->protocol == "ub" && !use_mmap_segment) { + // Only allocate_buffer_allocator_memory() memory goes back + // through the UB free path; hugepage mmaps fall through to + // munmap below. ub_segment_ptrs_.emplace_back(ptr, UbSegmentDeleter{mapped_size}); } else if (use_mmap_segment) { diff --git a/mooncake-store/tests/CMakeLists.txt b/mooncake-store/tests/CMakeLists.txt index f30e160327c..15f730e65b6 100644 --- a/mooncake-store/tests/CMakeLists.txt +++ b/mooncake-store/tests/CMakeLists.txt @@ -365,6 +365,20 @@ if(USE_TENT) set_tests_properties(standalone_client_tent_test PROPERTIES ENVIRONMENT "MC_USE_TENT=1;MC_FORCE_TCP=1") endif() +# Store over TENT UB without hardware. Keep UB-only assertions separate from +# the general Store integration and hugepage regression suites. +if(USE_TENT AND USE_UB_MOCK) + add_store_test(store_tent_ub_mock_test store_tent_ub_mock_test.cpp) + target_link_libraries(store_tent_ub_mock_test PRIVATE tent) + target_include_directories( + store_tent_ub_mock_test + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../../mooncake-transfer-engine/tent/tests/ub_mock) + set(STORE_UB_MOCK_ENV + "MC_USE_TENT=1;MC_TENT_UB_MOCK=1;MC_TENT_CONF={\"transports\":{\"tcp\":{\"enable\":false},\"rdma\":{\"enable\":false},\"hp_tcp\":{\"enable\":false},\"shm\":{\"enable\":false},\"io_uring\":{\"enable\":false},\"ub\":{\"enable\":true}}}" + ) + set_tests_properties(store_tent_ub_mock_test + PROPERTIES ENVIRONMENT "${STORE_UB_MOCK_ENV}" TIMEOUT 300) +endif() if(USE_CUDA) target_compile_definitions(pybind_client_test PRIVATE MOONCAKE_TEST_CUDA_H2D) target_link_libraries(pybind_client_test PRIVATE CUDA::cudart) diff --git a/mooncake-store/tests/ha/master_service_ha_test.cpp b/mooncake-store/tests/ha/master_service_ha_test.cpp index eec920e6582..a2894add56b 100644 --- a/mooncake-store/tests/ha/master_service_ha_test.cpp +++ b/mooncake-store/tests/ha/master_service_ha_test.cpp @@ -6651,9 +6651,7 @@ TEST_F(MasterServiceHATest, InvalidMountLogEntryLeavesNoSegmentOrClient) { EXPECT_FALSE( MasterServiceTestPeer::SegmentManager(service).GetSegmentBasicInfo( segment.id, name, endpoint)); - EXPECT_FALSE( - MasterServiceTestPeer::ClientLivenessRecords(service).contains( - client)); + EXPECT_FALSE(MasterServiceTestPeer(service).FindClientRecord(client)); } // The limit itself is legal. Correcting the request must mount and log it, // rather than finding state left behind by the rejected request. @@ -6692,8 +6690,7 @@ TEST_F(MasterServiceHATest, InvalidRemountLogEntryRejectsTheWholeGroup) { auto& manager = MasterServiceTestPeer::SegmentManager(service); EXPECT_FALSE(manager.GetSegmentBasicInfo(first.id, name, endpoint)); EXPECT_FALSE(manager.GetSegmentBasicInfo(second.id, name, endpoint)); - EXPECT_FALSE( - MasterServiceTestPeer::ClientLivenessRecords(service).contains(client)); + EXPECT_FALSE(MasterServiceTestPeer(service).FindClientRecord(client)); second.name.resize(kMaxOpLogObjectKeySize); ASSERT_TRUE(service.ReMountSegment({first, second}, client)); OpLogBatchStorage storage(cluster_id, *backend); diff --git a/mooncake-store/tests/store_tent_ub_mock_test.cpp b/mooncake-store/tests/store_tent_ub_mock_test.cpp new file mode 100644 index 00000000000..ecab4a426fd --- /dev/null +++ b/mooncake-store/tests/store_tent_ub_mock_test.cpp @@ -0,0 +1,151 @@ +// Copyright 2026 KVCache.AI +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "allocator.h" +#include "client_service.h" +#include "common/client_buffer_allocation.h" +#include "loopback_urma_adapter.h" +#include "real_client.h" +#include "test_server_helpers.h" + +namespace mooncake { +namespace testing { +namespace { + +long hugepagesFree() { + std::ifstream file("/proc/meminfo"); + std::string key; + long value = -1; + while (file >> key) { + if (key == "HugePages_Free:") { + file >> value; + break; + } + file.ignore(std::numeric_limits::max(), '\n'); + } + return value; +} + +class StoreTentUbMockTest : public ::testing::Test { + protected: + static void SetUpTestSuite() { + google::InitGoogleLogging("StoreTentUbMockTest"); + FLAGS_logtostderr = 1; + // Set before RealClient first reads its segment allocation policy. + setenv("MC_STORE_USE_HUGEPAGE", "1", 1); + } + + static void TearDownTestSuite() { google::ShutdownGoogleLogging(); } + + void SetUp() override { + ASSERT_TRUE(tent::ub::mock::loopbackRequested()); + ASSERT_TRUE(master_.Start(InProcMasterConfigBuilder().build())); + } + + void TearDown() override { master_.Stop(); } + + InProcMaster master_; +}; + +TEST_F(StoreTentUbMockTest, PutAndGetUseUb) { + namespace ub_mock = tent::ub::mock; + constexpr size_t kSize = 1024 * 1024; + constexpr size_t kSegmentSize = 512 * 1024 * 1024; + constexpr size_t kBufferSize = 128 * 1024 * 1024; + + auto provider = Client::Create("localhost:17812", "P2PHANDSHAKE", "ub", + std::nullopt, master_.master_address()); + ASSERT_TRUE(provider.has_value()); + auto client = Client::Create("localhost:17813", "P2PHANDSHAKE", "ub", + std::nullopt, master_.master_address()); + ASSERT_TRUE(client.has_value()); + + void* segment = allocate_buffer_allocator_memory(kSegmentSize); + ASSERT_NE(segment, nullptr); + auto mounted = (*provider)->MountSegment(segment, kSegmentSize, "ub"); + ASSERT_TRUE(mounted.has_value()) << toString(mounted.error()); + + SimpleAllocator buffers(kBufferSize); + auto registered = (*client)->RegisterLocalMemory( + buffers.getBase(), kBufferSize, "cpu:0", false, false); + ASSERT_TRUE(registered.has_value()) << toString(registered.error()); + + void* source = buffers.allocate(kSize); + void* target = buffers.allocate(kSize); + ASSERT_NE(source, nullptr); + ASSERT_NE(target, nullptr); + for (size_t i = 0; i < kSize; ++i) { + static_cast(source)[i] = static_cast(i * 13 + 7); + } + std::memset(target, 0, kSize); + ub_mock::resetLoopbackStats(); + + ReplicateConfig config; + config.replica_num = 1; + std::vector slices{{source, kSize}}; + auto put = (*client)->Put("ub_mock_put_get_key", slices, config); + ASSERT_TRUE(put.has_value()) << toString(put.error()); + const auto after_put = ub_mock::loopbackStats(); + EXPECT_GT(after_put.write_requests, 0u); + EXPECT_GE(after_put.bytes, kSize); + + slices = {{target, kSize}}; + auto get = (*client)->Get("ub_mock_put_get_key", slices); + ASSERT_TRUE(get.has_value()) << toString(get.error()); + EXPECT_EQ(std::memcmp(target, source, kSize), 0); + const auto after_get = ub_mock::loopbackStats(); + EXPECT_GT(after_get.read_requests, 0u); + EXPECT_GE(after_get.bytes - after_put.bytes, kSize); + + buffers.deallocate(source, kSize); + buffers.deallocate(target, kSize); + EXPECT_TRUE( + (*client)->unregisterLocalMemory(buffers.getBase(), false).has_value()); + EXPECT_TRUE((*provider)->UnmountSegment(segment, kSegmentSize).has_value()); + std::free(segment); +} + +TEST_F(StoreTentUbMockTest, HugepageSegmentIsReleasedOnTeardown) { + const long before = hugepagesFree(); + if (before <= 0) GTEST_SKIP() << "No free hugepages on this host"; + + auto client = RealClient::create(); + ASSERT_EQ(client->setup_real("localhost:17817", "P2PHANDSHAKE", + 16 * 1024 * 1024, 16 * 1024 * 1024, "ub", "", + master_.master_address()), + 0); + ASSERT_LT(hugepagesFree(), before) << "setup did not map hugepages"; + + client->tearDownAll(); + client.reset(); + EXPECT_EQ(hugepagesFree(), before) + << "hugepages mapped by setup were not released on teardown"; +} + +} // namespace +} // namespace testing +} // namespace mooncake diff --git a/mooncake-transfer-engine/benchmark/CMakeLists.txt b/mooncake-transfer-engine/benchmark/CMakeLists.txt index 2677aac9c0d..39712a0b8de 100644 --- a/mooncake-transfer-engine/benchmark/CMakeLists.txt +++ b/mooncake-transfer-engine/benchmark/CMakeLists.txt @@ -172,6 +172,16 @@ if(BUILD_UNIT_TESTS) set_tests_properties( tebench_reject_zero_duration PROPERTIES PASS_REGULAR_EXPRESSION "--duration must be positive" TIMEOUT 10) + add_test( + NAME tebench_reject_negative_warmup + COMMAND + ${CMAKE_COMMAND} -E env ${TEBENCH_HELP_ENV} $ + --backend=classic --xport_type=tcp --target_seg_name=127.0.0.1:1 + --warmup_ms=-1) + set_tests_properties( + tebench_reject_negative_warmup + PROPERTIES PASS_REGULAR_EXPRESSION "--warmup_ms must be non-negative" + TIMEOUT 10) # Target mode on the classic backend, which used to start with no buffers. add_test( NAME tebench_reject_unknown_seg_type diff --git a/mooncake-transfer-engine/benchmark/bench_config.cpp b/mooncake-transfer-engine/benchmark/bench_config.cpp index 9633d1d0a5d..2d9b777374f 100644 --- a/mooncake-transfer-engine/benchmark/bench_config.cpp +++ b/mooncake-transfer-engine/benchmark/bench_config.cpp @@ -198,6 +198,9 @@ bool validateSweep(std::string* error) { if (XferBenchConfig::duration <= 0) { return fail(error, "--duration must be positive"); } + if (XferBenchConfig::warmup_ms < 0) { + return fail(error, "--warmup_ms must be non-negative"); + } return true; } diff --git a/mooncake-transfer-engine/benchmark/main.cpp b/mooncake-transfer-engine/benchmark/main.cpp index b7395b67820..899cecceccd 100644 --- a/mooncake-transfer-engine/benchmark/main.cpp +++ b/mooncake-transfer-engine/benchmark/main.cpp @@ -60,6 +60,7 @@ int processBatchSizes( const bool read_verify = op_mode.read_verify; const OpCode opcode = op_mode.opcode; const bool random_access = op_mode.random_access; + const uint64_t warmup_ns = XferBenchConfig::warmup_ms * 1000000ull; XferBenchStats stats; std::vector qos_stats(qos_classes.size()); @@ -189,7 +190,7 @@ int processBatchSizes( XferBenchTimer timer; setSplitWarmup(true); - while (timer.lap_ns(false) < 1000ull * 1000 * 1000) { // 1 s + while (timer.lap_ns(false) < warmup_ns) { if (runner.runSingleTransfer( local_addr, target_id, nextTargetAddr(), thread_block_size, thread_batch_size, opcode, deadlineNs(), intent_type) < 0) { @@ -212,13 +213,9 @@ int processBatchSizes( if (mixed_opcode) { while (timer.lap_us(false) < XferBenchConfig::duration * 1000000ull) { - const size_t bytes = - checkedMul(thread_block_size, thread_batch_size, - "consistency payload size"); - const uint64_t batch_bytes = bytes; uint8_t pattern = 0; if (XferBenchConfig::check_consistency) - pattern = fillData((void*)local_addr, bytes); + pattern = fillData((void*)local_addr, op_bytes); // Read back from where this iteration wrote. const uint64_t op_target_addr = nextTargetAddr(); paceRequest(); @@ -226,37 +223,28 @@ int processBatchSizes( local_addr, target_id, op_target_addr, thread_block_size, thread_batch_size, WRITE, deadlineNs(), intent_type); if (val < 0) return failTask(); - thread_instant_bandwidth.push_back( - gbPerSecond(batch_bytes, val)); + thread_instant_bandwidth.push_back(gbPerSecond(op_bytes, val)); transfer_duration.push_back(val); // Clobber the local copy so the READ must bring the data // back; a value distinct from pattern keeps a no-op READ // from passing verification. if (XferBenchConfig::check_consistency) - fillData((void*)local_addr, bytes, pattern ^ 0xFF); + fillData((void*)local_addr, op_bytes, pattern ^ 0xFF); paceRequest(); val = runner.runSingleTransfer( local_addr, target_id, op_target_addr, thread_block_size, thread_batch_size, READ, deadlineNs(), intent_type); if (val < 0) return failTask(); - thread_instant_bandwidth.push_back( - gbPerSecond(batch_bytes, val)); + thread_instant_bandwidth.push_back(gbPerSecond(op_bytes, val)); if (XferBenchConfig::check_consistency) - verifyData((void*)local_addr, - checkedMul(thread_block_size, thread_batch_size, - "consistency payload size"), - pattern); + verifyData((void*)local_addr, op_bytes, pattern); transfer_duration.push_back(val); } } else { while (timer.lap_us(false) < XferBenchConfig::duration * 1000000ull) { - const size_t bytes = - checkedMul(thread_block_size, thread_batch_size, - "operation payload size"); - const uint64_t batch_bytes = bytes; if (write_seed) { - fillData((void*)local_addr, bytes, + fillData((void*)local_addr, op_bytes, stableDataSeed(target_addr)); } paceRequest(); @@ -264,21 +252,17 @@ int processBatchSizes( local_addr, target_id, nextTargetAddr(), thread_block_size, thread_batch_size, opcode, deadlineNs(), intent_type); if (val < 0) return failTask(); - thread_instant_bandwidth.push_back( - gbPerSecond(batch_bytes, val)); + thread_instant_bandwidth.push_back(gbPerSecond(op_bytes, val)); if (read_verify) { - verifyData((void*)local_addr, bytes, + verifyData((void*)local_addr, op_bytes, stableDataSeed(target_addr)); } transfer_duration.push_back(val); } } auto total_duration = timer.lap_us(); - const uint64_t bytes_per_operation = checkedMul( - thread_block_size, thread_batch_size, "operation payload size"); - const uint64_t transferred_bytes = - checkedMul(bytes_per_operation, transfer_duration.size(), - "thread transferred bytes"); + const uint64_t transferred_bytes = checkedMul( + op_bytes, transfer_duration.size(), "thread transferred bytes"); std::lock_guard lock(mutex); stats.total_duration.add(total_duration); stats.transfer_duration.add(transfer_duration); diff --git a/mooncake-transfer-engine/benchmark/te_backend.cpp b/mooncake-transfer-engine/benchmark/te_backend.cpp index 543b5ee30cf..f84b545493a 100644 --- a/mooncake-transfer-engine/benchmark/te_backend.cpp +++ b/mooncake-transfer-engine/benchmark/te_backend.cpp @@ -784,6 +784,7 @@ double TEBenchRunner::runSingleTransfer(uint64_t local_addr, uint64_t target_id, return -1.0; } std::vector requests; + requests.reserve(batch_size); for (uint64_t i = 0; i < batch_size; ++i) { TransferRequest entry; entry.opcode = diff --git a/mooncake-transfer-engine/benchmark/tent_backend.cpp b/mooncake-transfer-engine/benchmark/tent_backend.cpp index 39aff12ae81..5077b90217a 100644 --- a/mooncake-transfer-engine/benchmark/tent_backend.cpp +++ b/mooncake-transfer-engine/benchmark/tent_backend.cpp @@ -535,6 +535,7 @@ double TENTBenchRunner::runSingleTransfer( }; std::vector requests; + requests.reserve(batch_size); for (uint64_t i = 0; i < batch_size; ++i) { Request entry; entry.opcode = opcode == READ ? Request::READ : Request::WRITE; diff --git a/mooncake-transfer-engine/benchmark/utils.cpp b/mooncake-transfer-engine/benchmark/utils.cpp index 287c814fa64..f5b7a8eebf5 100644 --- a/mooncake-transfer-engine/benchmark/utils.cpp +++ b/mooncake-transfer-engine/benchmark/utils.cpp @@ -54,6 +54,8 @@ DEFINE_uint64(max_block_size, 1UL << 26, "Maximum block size (in bytes)."); DEFINE_uint64(start_batch_size, 1, "Start batch size (number of requests)."); DEFINE_uint64(max_batch_size, 1, "Maximum batch size (number of requests)."); DEFINE_int32(duration, 5, "Number of duration per test case."); +DEFINE_int32(warmup_ms, 1000, + "Warmup time per test case in milliseconds (0 disables warmup)."); DEFINE_int32(start_num_threads, 1, "Start number of concurrent worker threads."); DEFINE_int32(max_num_threads, 1, @@ -180,6 +182,7 @@ size_t XferBenchConfig::max_block_size = 0; size_t XferBenchConfig::start_batch_size = 0; size_t XferBenchConfig::max_batch_size = 0; int XferBenchConfig::duration = 0; +int XferBenchConfig::warmup_ms = 1000; int XferBenchConfig::max_num_threads = 0; int XferBenchConfig::start_num_threads = 0; size_t XferBenchConfig::target_offset = 0; @@ -294,6 +297,7 @@ void XferBenchConfig::loadFromFlags() { deadline_tight_threads = FLAGS_deadline_tight_threads; deadline_bw_arbitration = FLAGS_deadline_bw_arbitration; duration = FLAGS_duration; + warmup_ms = FLAGS_warmup_ms; metadata_type = FLAGS_metadata_type; metadata_url_list = FLAGS_metadata_url_list; diff --git a/mooncake-transfer-engine/benchmark/utils.h b/mooncake-transfer-engine/benchmark/utils.h index e29b7bcd04c..9fcd92fde2f 100644 --- a/mooncake-transfer-engine/benchmark/utils.h +++ b/mooncake-transfer-engine/benchmark/utils.h @@ -80,6 +80,7 @@ struct XferBenchConfig { static size_t start_batch_size; static size_t max_batch_size; static int duration; + static int warmup_ms; static int max_num_threads; static int start_num_threads; static size_t target_offset; diff --git a/mooncake-transfer-engine/tent/src/python/CMakeLists.txt b/mooncake-transfer-engine/tent/src/python/CMakeLists.txt index 66b86ebce79..103b4aab335 100644 --- a/mooncake-transfer-engine/tent/src/python/CMakeLists.txt +++ b/mooncake-transfer-engine/tent/src/python/CMakeLists.txt @@ -52,4 +52,12 @@ if(BUILD_UNIT_TESTS) "LD_LIBRARY_PATH=${CMAKE_BINARY_DIR}/mooncake-common:$:$ENV{LD_LIBRARY_PATH}" ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/../../tests/test_python_wait_transfer.py) + + add_test( + NAME tent_python_arrays_test + COMMAND + ${CMAKE_COMMAND} -E env "PYTHONPATH=$" + "LD_LIBRARY_PATH=${CMAKE_BINARY_DIR}/mooncake-common:$:$ENV{LD_LIBRARY_PATH}" + ${Python3_EXECUTABLE} + ${CMAKE_CURRENT_SOURCE_DIR}/../../tests/test_python_arrays.py) endif() diff --git a/mooncake-transfer-engine/tent/src/python/pybind.cpp b/mooncake-transfer-engine/tent/src/python/pybind.cpp index abbe9ab0e49..b36590bdf64 100644 --- a/mooncake-transfer-engine/tent/src/python/pybind.cpp +++ b/mooncake-transfer-engine/tent/src/python/pybind.cpp @@ -12,9 +12,11 @@ // See the License for the specific language governing permissions and // limitations under the License. +#include #include #include +#include #include #include #include @@ -137,6 +139,22 @@ static inline std::vector U64VectorToPtrVector( return ptrs; } +static inline bool IsUint64Vector(const py::array& array) { + if (array.ndim() != 1 || !array.dtype().is(py::dtype::of())) { + return false; + } + // numpy reports a zero stride for empty arrays, so the stride check only + // applies when there is an element to address. + return array.size() == 0 || + array.strides(0) == static_cast(sizeof(uint64_t)); +} + +// Bound for the wait after a failed batch. A task sitting behind the QP retry +// timer (send_timeout 14 ~= 67 ms, send_retry_count 7) needs up to ~540 ms to +// finish. At the deadline the engine cancels what is still running and reports +// the statuses it sees, so the caller learns whether the buffers are idle. +constexpr uint64_t kSettleTimeoutMs = 600; + // ============================================================================= // RAII Wrappers // ============================================================================= @@ -761,6 +779,139 @@ PYBIND11_MODULE(tent, m) { }, py::arg("batch_id"), py::arg("timeout_ms") = 0) + // --------------------------------------------------------------------- + // array submit and blocking wait + // --------------------------------------------------------------------- + .def( + "transfer_sync_arrays", + [](TransferEngine& self, py::array src, py::array dst, + py::array lengths, uint64_t target_id, + Request::OpCode opcode) -> py::array_t { + const auto count = static_cast(src.size()); + const bool well_formed = + IsUint64Vector(src) && IsUint64Vector(dst) && + IsUint64Vector(lengths) && src.size() == dst.size() && + src.size() == lengths.size(); + if (!well_formed && count == 0) { + ThrowStatus( + Status::InvalidArgument( + "src, dst and lengths must be one-dimensional " + "uint64 arrays of equal length" LOC_MARK), + "transfer_sync_arrays"); + } + py::array_t result(static_cast(count)); + if (count == 0) { + return result; + } + auto* states = result.mutable_data(); + std::fill(states, states + count, + static_cast(TransferStatusEnum::INVALID)); + if (!well_formed) { + return result; + } + const auto* src_ptr = static_cast(src.data()); + const auto* dst_ptr = static_cast(dst.data()); + const auto* len_ptr = + static_cast(lengths.data()); + std::string wait_error; + Status transfer_error; + { + py::gil_scoped_release release; + std::vector request_list(count); + for (size_t i = 0; i < count; ++i) { + auto& request = request_list[i]; + request.opcode = opcode; + request.source = U64ToPtr(src_ptr[i]); + request.target_id = static_cast(target_id); + request.target_offset = dst_ptr[i]; + request.length = static_cast(len_ptr[i]); + } + const auto batch_id = self.allocateBatch(count); + if (!batch_id) { + transfer_error = Status::TooManyRequests( + "No free batch slot for a transfer_sync_arrays " + "call" LOC_MARK); + } else { + BatchGuard guard(&self, + static_cast(batch_id)); + // A failed submit or wait leaves ownership with the + // transport; ask it to stop before the guard frees the + // batch, or the caller may reuse live buffers. + const auto settled = [&] { + std::vector settle_status; + auto status = self.waitTransfer( + batch_id, &settle_status, kSettleTimeoutMs); + if (!status.ok()) return false; + return settle_status.size() == count && + std::none_of( + settle_status.begin(), + settle_status.end(), + [](const TransferStatus& item) { + return item.s == + TransferStatusEnum::PENDING; + }); + }; + auto submit_status = + self.submitTransfer(batch_id, request_list); + if (!submit_status.ok()) { + if (!settled()) { + wait_error = + "submitTransfer failed: " + + submit_status.ToString() + + "; the batch may still access src and dst, " + "so do not reuse them"; + } + } else { + std::vector status_list; + auto wait_status = + self.waitTransfer(batch_id, &status_list, 0); + if (!wait_status.ok()) { + wait_error = "waitTransfer failed: " + + wait_status.ToString(); + if (!settled()) { + wait_error += + "; the batch may still access src and " + "dst, so do not reuse them"; + } + } else if (status_list.size() != count) { + wait_error = + "waitTransfer returned " + + std::to_string(status_list.size()) + + " statuses for " + std::to_string(count) + + " descriptors" LOC_MARK; + } else { + for (size_t i = 0; i < count; ++i) { + states[i] = + static_cast(status_list[i].s); + } + } + } + } + } + if (!wait_error.empty()) { + ThrowStatus(Status::InternalError(wait_error), + "transfer_sync_arrays"); + } + if (!transfer_error.ok()) { + ThrowStatus(transfer_error, "transfer_sync_arrays"); + } + return result; + }, + "Submit src to dst descriptors in one batch and wait until every " + "descriptor reaches a terminal state. src, dst and lengths are " + "one-dimensional uint64 arrays of equal length and must not be " + "modified until the call returns. Malformed non-empty input is " + "reported as INVALID for every entry; an empty input that is not " + "three empty uint64 vectors raises InvalidArgumentError; running " + "out of batch slots raises TooManyRequests. A failed submit or " + "wait waits one RDMA retry budget (600 ms) for every descriptor to " + "stop, cancelling whatever still runs at the deadline; if " + "descriptors are still pending then, the call raises " + "InternalError, which says src and dst must not be reused. This " + "call has no timeout.", + py::arg("src"), py::arg("dst"), py::arg("lengths"), + py::arg("target_id"), py::arg("opcode")) + // --------------------------------------------------------------------- // notification send/receive // --------------------------------------------------------------------- diff --git a/mooncake-transfer-engine/tent/src/transport/ub/CMakeLists.txt b/mooncake-transfer-engine/tent/src/transport/ub/CMakeLists.txt index 89035a84c2b..57ee883842e 100644 --- a/mooncake-transfer-engine/tent/src/transport/ub/CMakeLists.txt +++ b/mooncake-transfer-engine/tent/src/transport/ub/CMakeLists.txt @@ -5,4 +5,15 @@ if(USE_UB) if(URMA_LIBRARY) target_compile_definitions(tent_xport_ub PRIVATE TENT_HAS_REAL_URMA=1) endif() + # Test-only loopback adapter. Its source lives under tests/ and is linked in + # only when USE_UB_MOCK=ON, so normal builds are unchanged. + if(USE_UB_MOCK) + set(TENT_UB_MOCK_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../../../tests/ub_mock) + target_sources(tent_xport_ub + PRIVATE ${TENT_UB_MOCK_DIR}/loopback_urma_adapter.cpp) + target_include_directories(tent_xport_ub PUBLIC ${TENT_UB_MOCK_DIR}) + target_compile_definitions(tent_xport_ub PRIVATE TENT_UB_MOCK_ADAPTER=1) + message(WARNING "USE_UB_MOCK is ON: TENT UB includes a test-only " + "loopback adapter (MC_TENT_UB_MOCK=1 enables it)") + endif() endif() diff --git a/mooncake-transfer-engine/tent/src/transport/ub/urma_adapter.cpp b/mooncake-transfer-engine/tent/src/transport/ub/urma_adapter.cpp index eaaac170883..fd4841a4af8 100644 --- a/mooncake-transfer-engine/tent/src/transport/ub/urma_adapter.cpp +++ b/mooncake-transfer-engine/tent/src/transport/ub/urma_adapter.cpp @@ -14,6 +14,10 @@ #include "tent/transport/ub/urma_adapter.h" +#if defined(TENT_UB_MOCK_ADAPTER) && TENT_UB_MOCK_ADAPTER +#include "loopback_urma_adapter.h" +#endif + #include #include #include @@ -1700,6 +1704,11 @@ class RealUrmaAdapter final : public UrmaAdapter { } // namespace std::shared_ptr createDefaultUrmaAdapter() { +#if defined(TENT_UB_MOCK_ADAPTER) && TENT_UB_MOCK_ADAPTER + // Test-only builds (USE_UB_MOCK=ON): MC_TENT_UB_MOCK=1 selects the + // in-process loopback adapter instead of liburma. + if (mock::loopbackRequested()) return mock::createLoopbackUrmaAdapter(); +#endif #if defined(TENT_HAS_REAL_URMA) && TENT_HAS_REAL_URMA return std::make_shared(); #else diff --git a/mooncake-transfer-engine/tent/tests/CMakeLists.txt b/mooncake-transfer-engine/tent/tests/CMakeLists.txt index 8f4335e1161..1626ff2582a 100644 --- a/mooncake-transfer-engine/tent/tests/CMakeLists.txt +++ b/mooncake-transfer-engine/tent/tests/CMakeLists.txt @@ -634,6 +634,21 @@ if(USE_UB) PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../include) add_test(NAME tent_ub_native_data_path_test COMMAND tent_ub_native_data_path_test) + + # Engine-level UB run on the test-only loopback adapter (no UB hardware). + if(USE_UB_MOCK) + add_executable(tent_ub_loopback_engine_test ub_loopback_engine_test.cpp) + target_link_libraries(tent_ub_loopback_engine_test PRIVATE gtest gtest_main + tent_link_group) + target_include_directories( + tent_ub_loopback_engine_test + PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/../include + ${CMAKE_CURRENT_SOURCE_DIR}/ub_mock) + add_test(NAME tent_ub_loopback_engine_test + COMMAND tent_ub_loopback_engine_test) + set_tests_properties(tent_ub_loopback_engine_test + PROPERTIES ENVIRONMENT "MC_TENT_UB_MOCK=1" TIMEOUT 120) + endif() endif() # End-to-end failover test: drives real TransferEngineImpl with diff --git a/mooncake-transfer-engine/tent/tests/test_python_arrays.py b/mooncake-transfer-engine/tent/tests/test_python_arrays.py new file mode 100644 index 00000000000..1216224f2d8 --- /dev/null +++ b/mooncake-transfer-engine/tent/tests/test_python_arrays.py @@ -0,0 +1,150 @@ +import ctypes +import json +import tempfile +import unittest +from pathlib import Path + +import numpy as np +import tent + +COMPLETED = int(tent.TransferStatusEnum.COMPLETED) +INVALID = int(tent.TransferStatusEnum.INVALID) + + +def write_config(directory, name): + config = Path(directory) / name + config.write_text( + json.dumps( + { + "metadata_type": "p2p", + "rpc_server_hostname": "127.0.0.1", + "rpc_server_port": 0, + "transports": { + "tcp": {"enable": True}, + "hp_tcp": {"enable": False}, + "rdma": {"enable": False}, + "shm": {"enable": False}, + }, + } + ) + ) + return str(config) + + +class ArrayEntryPointTest(unittest.TestCase): + def setUp(self): + self._directory = tempfile.TemporaryDirectory() + self.engine = tent.TransferEngine( + write_config(self._directory.name, "engine.json") + ) + + def tearDown(self): + self._directory.cleanup() + + def test_mismatched_lengths_report_invalid_states(self): + source = np.zeros(2, dtype=np.uint64) + target = np.zeros(2, dtype=np.uint64) + lengths = np.zeros(3, dtype=np.uint64) + states = self.engine.transfer_sync_arrays( + source, target, lengths, 0, tent.OpCode.WRITE + ) + self.assertEqual(states.tolist(), [INVALID, INVALID]) + + def test_two_dimensional_arrays_report_invalid_states(self): + source = np.zeros((2, 2), dtype=np.uint64) + target = np.zeros((2, 2), dtype=np.uint64) + lengths = np.zeros((2, 2), dtype=np.uint64) + states = self.engine.transfer_sync_arrays( + source, target, lengths, 0, tent.OpCode.WRITE + ) + self.assertEqual(states.tolist(), [INVALID] * 4) + + def test_non_uint64_input_reports_invalid_states(self): + source = np.zeros(2, dtype=np.float64) + target = np.zeros(2, dtype=np.float64) + lengths = np.zeros(2, dtype=np.float64) + states = self.engine.transfer_sync_arrays( + source, target, lengths, 0, tent.OpCode.WRITE + ) + self.assertEqual(states.tolist(), [INVALID, INVALID]) + + def test_strided_view_reports_invalid_states(self): + source = np.zeros(4, dtype=np.uint64)[::2] + target = np.zeros(4, dtype=np.uint64)[::2] + lengths = np.zeros(4, dtype=np.uint64)[::2] + states = self.engine.transfer_sync_arrays( + source, target, lengths, 0, tent.OpCode.WRITE + ) + self.assertEqual(states.tolist(), [INVALID, INVALID]) + + def test_empty_batch_returns_no_states(self): + empty = np.zeros(0, dtype=np.uint64) + states = self.engine.transfer_sync_arrays( + empty, empty, empty, 0, tent.OpCode.WRITE + ) + self.assertEqual(states.dtype, np.uint8) + self.assertEqual(states.shape, (0,)) + + def test_empty_non_uint64_input_raises(self): + empty = np.zeros(0, dtype=np.float64) + with self.assertRaises(tent.InvalidArgumentError): + self.engine.transfer_sync_arrays(empty, empty, empty, 0, tent.OpCode.WRITE) + + def test_empty_two_dimensional_input_raises(self): + empty = np.zeros((0, 0), dtype=np.uint64) + with self.assertRaises(tent.InvalidArgumentError): + self.engine.transfer_sync_arrays(empty, empty, empty, 0, tent.OpCode.WRITE) + + def test_empty_source_with_non_empty_target_raises(self): + source = np.zeros(0, dtype=np.uint64) + target = np.zeros(2, dtype=np.uint64) + lengths = np.zeros(0, dtype=np.uint64) + with self.assertRaises(tent.InvalidArgumentError): + self.engine.transfer_sync_arrays( + source, target, lengths, 0, tent.OpCode.WRITE + ) + + +class ArrayTransferTest(unittest.TestCase): + def test_write_and_read_move_bytes(self): + with tempfile.TemporaryDirectory() as directory: + server = tent.TransferEngine(write_config(directory, "server.json")) + client = tent.TransferEngine(write_config(directory, "client.json")) + buffer_size = 4096 + pattern = bytes(range(64)) * 64 + server_addr = server.allocate_local_memory(buffer_size) + client_addr = client.allocate_local_memory(buffer_size) + server.register_local_memory(server_addr, buffer_size) + client.register_local_memory(client_addr, buffer_size) + segment = None + try: + ctypes.memmove(client_addr, pattern, buffer_size) + segment = client.open_segment(server.get_segment_name()) + server_base = client.get_segment_info(segment).buffers[0].base + source = np.array([client_addr], dtype=np.uint64) + target = np.array([server_base], dtype=np.uint64) + lengths = np.array([buffer_size], dtype=np.uint64) + + states = client.transfer_sync_arrays( + source, target, lengths, segment, tent.OpCode.WRITE + ) + self.assertEqual(states.tolist(), [COMPLETED]) + self.assertEqual(ctypes.string_at(server_addr, buffer_size), pattern) + + ctypes.memset(client_addr, 0, buffer_size) + states = client.transfer_sync_arrays( + source, target, lengths, segment, tent.OpCode.READ + ) + self.assertEqual(states.tolist(), [COMPLETED]) + self.assertEqual(ctypes.string_at(client_addr, buffer_size), pattern) + finally: + if segment is not None: + client.close_segment(segment) + client.unregister_local_memory(client_addr, buffer_size) + server.unregister_local_memory(server_addr, buffer_size) + client.free_local_memory(client_addr) + server.free_local_memory(server_addr) + + +if __name__ == "__main__": + unittest.main() diff --git a/mooncake-transfer-engine/tent/tests/ub_loopback_engine_test.cpp b/mooncake-transfer-engine/tent/tests/ub_loopback_engine_test.cpp new file mode 100644 index 00000000000..27dd5af2602 --- /dev/null +++ b/mooncake-transfer-engine/tent/tests/ub_loopback_engine_test.cpp @@ -0,0 +1,205 @@ +// Copyright 2026 KVCache.AI +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Runs two TENT engines in one process with only the UB transport enabled and +// the loopback URMA adapter (USE_UB_MOCK=ON, MC_TENT_UB_MOCK=1). It checks +// that engine-level READ/WRITE goes through UbTransport end to end. + +#include + +#include +#include +#include +#include +#include +#include + +#include "loopback_urma_adapter.h" +#include "tent/common/config.h" +#include "tent/common/types.h" +#include "tent/transfer_engine.h" + +namespace mooncake { +namespace tent { +namespace { + +constexpr size_t kBufferLength = 4 * 1024 * 1024; + +std::shared_ptr makeUbOnlyConfig() { + auto config = std::make_shared(); + config->set("metadata_type", "p2p"); + config->set("metadata_servers", "P2PHANDSHAKE"); + config->set("transports/tcp/enable", false); + config->set("transports/rdma/enable", false); + config->set("transports/shm/enable", false); + config->set("transports/io_uring/enable", false); + config->set("transports/ub/enable", true); + config->set("transports/ub/worker_count", 2); + config->set("transports/ub/max_endpoints", 64); + // Small slices so one request is split across many work requests. + config->set("transports/ub/slice_size", 64 * 1024); + return config; +} + +int waitBatch(TransferEngine& engine, BatchID batch, int timeout_ms = 20000) { + TransferStatus status; + for (int i = 0; i < timeout_ms; ++i) { + auto result = engine.getTransferStatus(batch, status); + if (!result.ok() || status.s == TransferStatusEnum::FAILED) return -1; + if (status.s == TransferStatusEnum::COMPLETED) return 1; + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + return 0; +} + +uint8_t pattern(size_t i, size_t seed) { + return static_cast((i * 7 + seed * 131 + (i >> 12)) & 0xff); +} + +class UbLoopbackEngineTest : public ::testing::Test { + protected: + void SetUp() override { + if (!ub::mock::loopbackRequested()) { + GTEST_SKIP() << ub::mock::kLoopbackEnv << " is not set"; + } + ub::mock::resetLoopbackStats(); + + server_ = std::make_unique(makeUbOnlyConfig()); + client_ = std::make_unique(makeUbOnlyConfig()); + ASSERT_TRUE(server_->available()); + ASSERT_TRUE(client_->available()); + + server_buffer_.assign(kBufferLength, 0); + client_buffer_.assign(kBufferLength, 0); + ASSERT_TRUE( + server_->registerLocalMemory(server_buffer_.data(), kBufferLength) + .ok()); + ASSERT_TRUE( + client_->registerLocalMemory(client_buffer_.data(), kBufferLength) + .ok()); + auto status = client_->openSegment(segment_, server_->getSegmentName()); + ASSERT_TRUE(status.ok()) << status.ToString(); + } + + void TearDown() override { + if (client_) { + if (segment_) (void)client_->closeSegment(segment_); + (void)client_->unregisterLocalMemory(client_buffer_.data(), + kBufferLength); + } + if (server_) { + (void)server_->unregisterLocalMemory(server_buffer_.data(), + kBufferLength); + } + client_.reset(); + server_.reset(); + } + + Request makeRequest(Request::OpCode op, size_t offset, size_t length, + TransportType hint) { + Request request{}; + request.opcode = op; + request.source = client_buffer_.data() + offset; + request.target_id = segment_; + request.target_offset = + reinterpret_cast(server_buffer_.data()) + offset; + request.length = length; + request.transport_hint = hint; + return request; + } + + int run(const std::vector& requests) { + BatchID batch = client_->allocateBatch(requests.size()); + auto status = client_->submitTransfer(batch, requests); + if (!status.ok()) { + ADD_FAILURE() << status.ToString(); + (void)client_->freeBatch(batch); + return -2; + } + int done = waitBatch(*client_, batch); + (void)client_->freeBatch(batch); + return done; + } + + std::unique_ptr server_; + std::unique_ptr client_; + std::vector server_buffer_; + std::vector client_buffer_; + SegmentID segment_ = 0; +}; + +TEST_F(UbLoopbackEngineTest, WriteThenReadThroughUb) { + for (size_t i = 0; i < kBufferLength; ++i) { + client_buffer_[i] = pattern(i, 1); + } + ASSERT_EQ(run({makeRequest(Request::WRITE, 0, kBufferLength, UB)}), 1); + for (size_t i = 0; i < kBufferLength; ++i) { + ASSERT_EQ(server_buffer_[i], pattern(i, 1)) << "offset " << i; + } + + for (size_t i = 0; i < kBufferLength; ++i) { + server_buffer_[i] = pattern(i, 2); + } + std::fill(client_buffer_.begin(), client_buffer_.end(), 0); + ASSERT_EQ(run({makeRequest(Request::READ, 0, kBufferLength, UB)}), 1); + for (size_t i = 0; i < kBufferLength; ++i) { + ASSERT_EQ(client_buffer_[i], pattern(i, 2)) << "offset " << i; + } + + const auto stats = ub::mock::loopbackStats(); + EXPECT_GT(stats.write_requests, 0u); + EXPECT_GT(stats.read_requests, 0u); + EXPECT_EQ(stats.bytes, 2 * kBufferLength); +} + +// Without a transport hint the engine must still pick UB, since it is the only +// transport installed. +TEST_F(UbLoopbackEngineTest, UnhintedBatchUsesUb) { + std::vector requests; + constexpr size_t kChunk = 256 * 1024 + 17; + for (size_t offset = 0; offset + kChunk <= kBufferLength; + offset += kChunk + 3) { + for (size_t i = 0; i < kChunk; ++i) { + client_buffer_[offset + i] = pattern(offset + i, 3); + } + requests.push_back(makeRequest(Request::WRITE, offset, kChunk, UNSPEC)); + } + ASSERT_EQ(run(requests), 1); + for (const auto& request : requests) { + const size_t offset = + static_cast(request.source) - client_buffer_.data(); + for (size_t i = 0; i < request.length; ++i) { + ASSERT_EQ(server_buffer_[offset + i], pattern(offset + i, 3)) + << "offset " << offset + i; + } + } + EXPECT_GT(ub::mock::loopbackStats().write_requests, 0u); +} + +TEST_F(UbLoopbackEngineTest, OutOfRangeTargetFails) { + // The target range ends past the server's registered buffer. The engine + // may reject it at submit time or fail the task; it must not complete. + Request request = makeRequest(Request::WRITE, 0, 8192, UB); + request.target_offset += kBufferLength - 4096; + BatchID batch = client_->allocateBatch(1); + if (client_->submitTransfer(batch, {request}).ok()) { + EXPECT_NE(waitBatch(*client_, batch, 5000), 1); + } + (void)client_->freeBatch(batch); + EXPECT_EQ(ub::mock::loopbackStats().bytes, 0u); +} + +} // namespace +} // namespace tent +} // namespace mooncake diff --git a/mooncake-transfer-engine/tent/tests/ub_mock/loopback_urma_adapter.cpp b/mooncake-transfer-engine/tent/tests/ub_mock/loopback_urma_adapter.cpp new file mode 100644 index 00000000000..ea562941517 --- /dev/null +++ b/mooncake-transfer-engine/tent/tests/ub_mock/loopback_urma_adapter.cpp @@ -0,0 +1,393 @@ +// Copyright 2026 KVCache.AI +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "loopback_urma_adapter.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace mooncake { +namespace tent { +namespace ub { +namespace mock { +namespace { + +constexpr uint32_t kApiVersion = 1; +constexpr uint32_t kDescriptorSize = 16; + +std::atomic g_read_requests{0}; +std::atomic g_write_requests{0}; +std::atomic g_bytes{0}; + +DeviceInfo loopbackDevice() { + DeviceInfo info; + info.topology_name = "ub:mock0:eid0"; + info.native_device_name = "mock0"; + // Left empty so topology discovery does not look for a sysfs node. + info.native_device_path = ""; + info.eid_index = 0; + info.eid = "00ff:0000:0000:0000:0000:0000:0000:0001"; + info.active = true; + // Zero capabilities mean "no limit reported". + return info; +} + +// The descriptor carries "address:length" so any engine in the process can +// import a segment registered by another engine. +SegmentDescriptor makeDescriptor(uint64_t address, uint64_t length) { + return SegmentDescriptor{ + SegmentDescriptor::kSchemaVersion, kApiVersion, kDescriptorSize, + std::to_string(address) + ":" + std::to_string(length)}; +} + +bool parseDescriptor(const SegmentDescriptor& descriptor, uint64_t& address, + uint64_t& length) { + const auto colon = descriptor.hex.find(':'); + if (descriptor.schema_version != SegmentDescriptor::kSchemaVersion || + descriptor.urma_api_version != kApiVersion || + descriptor.urma_abi_size != kDescriptorSize || + colon == std::string::npos) { + return false; + } + try { + address = std::stoull(descriptor.hex.substr(0, colon)); + length = std::stoull(descriptor.hex.substr(colon + 1)); + return length != 0; + } catch (...) { + return false; + } +} + +bool contains(uint64_t base, uint64_t length, uint64_t address, size_t size) { + return address >= base && size <= length && address - base <= length - size; +} + +class LoopbackContext final : public Context { + public: + explicit LoopbackContext(DeviceInfo info) : info_(std::move(info)) {} + bool valid() const noexcept override { + return valid_.load(std::memory_order_acquire); + } + const DeviceInfo& deviceInfo() const noexcept override { return info_; } + int asyncFd() const noexcept override { return -1; } + void close() { valid_.store(false, std::memory_order_release); } + + private: + DeviceInfo info_; + std::atomic valid_{true}; +}; + +class LoopbackJfc final : public Jfc { + public: + bool valid() const noexcept override { + return valid_.load(std::memory_order_acquire); + } + int eventFd() const noexcept override { return -1; } + void close() { valid_.store(false, std::memory_order_release); } + + void push(const Completion& completion) { + std::lock_guard lock(mutex_); + completions_.push_back(completion); + } + void poll(size_t maximum, std::vector& output) { + std::lock_guard lock(mutex_); + while (!completions_.empty() && output.size() < maximum) { + output.push_back(completions_.front()); + completions_.pop_front(); + } + } + + private: + std::mutex mutex_; + std::deque completions_; + std::atomic valid_{true}; +}; + +template +class LoopbackSegment final : public Base { + public: + LoopbackSegment(uint64_t address, uint64_t length, + SegmentDescriptor descriptor) + : address_(address), + length_(length), + descriptor_(std::move(descriptor)) {} + bool valid() const noexcept override { + return valid_.load(std::memory_order_acquire); + } + uint64_t address() const noexcept override { return address_; } + uint64_t length() const noexcept override { return length_; } + const SegmentDescriptor& descriptor() const noexcept override { + return descriptor_; + } + void close() { valid_.store(false, std::memory_order_release); } + + private: + uint64_t address_; + uint64_t length_; + SegmentDescriptor descriptor_; + std::atomic valid_{true}; +}; + +using LoopbackLocalSegment = LoopbackSegment; +using LoopbackRemoteSegment = LoopbackSegment; + +class LoopbackJetty final : public Jetty { + public: + LoopbackJetty(uint32_t id, std::shared_ptr jfc) + : id_(id), jfc_(std::move(jfc)) {} + bool valid() const noexcept override { + return valid_.load(std::memory_order_acquire); + } + uint32_t id() const noexcept override { return id_; } + uint32_t uasid() const noexcept override { return 0; } + const std::shared_ptr& jfc() const { return jfc_; } + bool bound() const { return bound_.load(std::memory_order_acquire); } + void setBound(bool bound) { + bound_.store(bound, std::memory_order_release); + } + void close() { + valid_.store(false, std::memory_order_release); + setBound(false); + } + + private: + uint32_t id_; + std::shared_ptr jfc_; + std::atomic valid_{true}; + std::atomic bound_{false}; +}; + +class LoopbackUrmaAdapter final : public UrmaAdapter { + public: + bool available() const noexcept override { return true; } + uint32_t nativeApiVersion() const noexcept override { return kApiVersion; } + size_t nativeSegmentDescriptorSize() const noexcept override { + return kDescriptorSize; + } + + Status initialize() override { + initialized_.store(true, std::memory_order_release); + return Status::OK(); + } + Status shutdown() override { + initialized_.store(false, std::memory_order_release); + return Status::OK(); + } + Status discoverDevices(std::vector& devices) override { + if (!initialized_.load(std::memory_order_acquire)) { + return Status::InvalidArgument("loopback adapter not initialized"); + } + devices = {device_}; + return Status::OK(); + } + + Status openContext(const DeviceInfo& device, ContextPtr& context) override { + if (!initialized_.load(std::memory_order_acquire) || + device.topology_name != device_.topology_name) { + return Status::DeviceNotFound("loopback device missing"); + } + context = std::make_shared(device); + return Status::OK(); + } + Status closeContext(ContextPtr& context) override { + if (auto loopback = std::dynamic_pointer_cast(context)) + loopback->close(); + context.reset(); + return Status::OK(); + } + + Status createJfc(const ContextPtr&, const JfcOptions&, + JfcPtr& jfc) override { + jfc = std::make_shared(); + return Status::OK(); + } + Status deleteJfc(JfcPtr& jfc) override { + if (auto loopback = std::dynamic_pointer_cast(jfc)) + loopback->close(); + jfc.reset(); + return Status::OK(); + } + + Status registerLocalSegment(const ContextPtr&, uint64_t address, + size_t length, const SegmentOptions&, + LocalSegmentPtr& segment) override { + if (address == 0 || length == 0) { + return Status::InvalidArgument("empty loopback segment"); + } + segment = std::make_shared( + address, length, makeDescriptor(address, length)); + return Status::OK(); + } + Status unregisterLocalSegment(LocalSegmentPtr& segment) override { + if (auto loopback = + std::dynamic_pointer_cast(segment)) + loopback->close(); + segment.reset(); + return Status::OK(); + } + + Status importRemoteSegment(const ContextPtr&, + const SegmentDescriptor& descriptor, + const SegmentOptions&, + RemoteSegmentPtr& segment) override { + uint64_t address = 0; + uint64_t length = 0; + if (!parseDescriptor(descriptor, address, length)) { + return Status::InvalidArgument("bad loopback segment descriptor"); + } + segment = std::make_shared(address, length, + descriptor); + return Status::OK(); + } + Status unimportRemoteSegment(RemoteSegmentPtr& segment) override { + if (auto loopback = + std::dynamic_pointer_cast(segment)) + loopback->close(); + segment.reset(); + return Status::OK(); + } + + Status createJetty(const ContextPtr&, const JfcPtr& jfc, + const JettyOptions&, JettyPtr& jetty) override { + auto loopback_jfc = std::dynamic_pointer_cast(jfc); + if (!loopback_jfc) return Status::InvalidArgument("bad loopback JFC"); + jetty = std::make_shared( + next_jetty_id_.fetch_add(1, std::memory_order_relaxed), + std::move(loopback_jfc)); + return Status::OK(); + } + Status deleteJetty(JettyPtr& jetty) override { + if (auto loopback = std::dynamic_pointer_cast(jetty)) + loopback->close(); + jetty.reset(); + return Status::OK(); + } + Status bindJetty(const JettyPtr& jetty, const RemoteJettyInfo&) override { + auto loopback = std::dynamic_pointer_cast(jetty); + if (!loopback || !loopback->valid()) + return Status::InvalidArgument("bad loopback Jetty"); + loopback->setBound(true); + return Status::OK(); + } + Status unbindJetty(const JettyPtr& jetty) override { + if (auto loopback = std::dynamic_pointer_cast(jetty)) + loopback->setBound(false); + return Status::OK(); + } + Status resetJetty(const JettyPtr&) override { return Status::OK(); } + + // Every posted WR completes inside post(), so nothing is ever in flight. + Status quiesceJetty(const JettyPtr& jetty, uint32_t timeout_ms, + std::vector& completions) override { + completions.clear(); + auto loopback = std::dynamic_pointer_cast(jetty); + if (!loopback || !loopback->valid() || timeout_ms == 0) + return Status::InvalidArgument("bad loopback Jetty quiesce"); + return Status::OK(); + } + + Status post(const JettyPtr& jetty, const std::vector& requests, + size_t& posted_count) override { + posted_count = 0; + auto loopback = std::dynamic_pointer_cast(jetty); + if (!loopback || !loopback->valid() || !loopback->bound()) + return Status::InvalidArgument("unbound loopback Jetty"); + for (const auto& request : requests) { + if (!request.local_segment || !request.remote_segment || + request.token == 0 || request.length == 0) { + return Status::InvalidArgument("bad loopback WR"); + } + const auto& local = *request.local_segment; + const auto& remote = *request.remote_segment; + CompletionCategory category = CompletionCategory::SUCCESS; + if (!local.valid() || !remote.valid() || + !contains(local.address(), local.length(), + request.local_address, request.length) || + !contains(remote.address(), remote.length(), + request.remote_address, request.length)) { + category = CompletionCategory::MEMORY_ERROR; + } else if (request.operation == Operation::WRITE) { + std::memmove( + reinterpret_cast(request.remote_address), + reinterpret_cast(request.local_address), + request.length); + g_write_requests.fetch_add(1, std::memory_order_relaxed); + } else { + std::memmove( + reinterpret_cast(request.local_address), + reinterpret_cast(request.remote_address), + request.length); + g_read_requests.fetch_add(1, std::memory_order_relaxed); + } + const bool ok = category == CompletionCategory::SUCCESS; + if (ok) + g_bytes.fetch_add(request.length, std::memory_order_relaxed); + loopback->jfc()->push( + Completion{category, ok ? 0 : -1, request.token, + ok ? static_cast(request.length) : 0, + loopback->id()}); + ++posted_count; + } + return Status::OK(); + } + + Status poll(const JfcPtr& jfc, size_t maximum, + std::vector& completions) override { + completions.clear(); + auto loopback = std::dynamic_pointer_cast(jfc); + if (!loopback || !loopback->valid()) + return Status::InvalidArgument("bad loopback JFC"); + loopback->poll(maximum, completions); + return Status::OK(); + } + + private: + const DeviceInfo device_ = loopbackDevice(); + std::atomic initialized_{false}; + std::atomic next_jetty_id_{1}; +}; + +} // namespace + +std::shared_ptr createLoopbackUrmaAdapter() { + return std::make_shared(); +} + +bool loopbackRequested() { + const char* value = std::getenv(kLoopbackEnv); + return value && value[0] != '\0' && std::strcmp(value, "0") != 0; +} + +LoopbackStats loopbackStats() { + return LoopbackStats{g_read_requests.load(std::memory_order_relaxed), + g_write_requests.load(std::memory_order_relaxed), + g_bytes.load(std::memory_order_relaxed)}; +} + +void resetLoopbackStats() { + g_read_requests.store(0, std::memory_order_relaxed); + g_write_requests.store(0, std::memory_order_relaxed); + g_bytes.store(0, std::memory_order_relaxed); +} + +} // namespace mock +} // namespace ub +} // namespace tent +} // namespace mooncake diff --git a/mooncake-transfer-engine/tent/tests/ub_mock/loopback_urma_adapter.h b/mooncake-transfer-engine/tent/tests/ub_mock/loopback_urma_adapter.h new file mode 100644 index 00000000000..93b3126a3da --- /dev/null +++ b/mooncake-transfer-engine/tent/tests/ub_mock/loopback_urma_adapter.h @@ -0,0 +1,58 @@ +// Copyright 2026 KVCache.AI +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef TENT_TESTS_UB_MOCK_LOOPBACK_URMA_ADAPTER_H_ +#define TENT_TESTS_UB_MOCK_LOOPBACK_URMA_ADAPTER_H_ + +#include +#include + +#include "tent/transport/ub/urma_adapter.h" + +namespace mooncake { +namespace tent { +namespace ub { +namespace mock { + +// Test-only URMA adapter for builds without UB hardware. It reports one fake +// UB device and carries READ/WRITE work requests with memcpy, so it only works +// when both ends live in the same process (e.g. in-process Store tests). +// +// It is compiled only with -DUSE_UB_MOCK=ON. In such a build the default +// adapter factory returns it when MC_TENT_UB_MOCK=1 is set; otherwise the +// factory behaves as in a normal build. +std::shared_ptr createLoopbackUrmaAdapter(); + +// Name of the environment variable that turns the loopback adapter on. +inline constexpr const char* kLoopbackEnv = "MC_TENT_UB_MOCK"; + +// True when kLoopbackEnv is set to a non-empty value other than "0". +bool loopbackRequested(); + +// Process-wide counters across all loopback adapter instances, so tests can +// check that data really went through the UB transport. +struct LoopbackStats { + uint64_t read_requests = 0; + uint64_t write_requests = 0; + uint64_t bytes = 0; +}; +LoopbackStats loopbackStats(); +void resetLoopbackStats(); + +} // namespace mock +} // namespace ub +} // namespace tent +} // namespace mooncake + +#endif // TENT_TESTS_UB_MOCK_LOOPBACK_URMA_ADAPTER_H_ diff --git a/scripts/generate_hardware_overview.py b/scripts/generate_hardware_overview.py index 583ad8bf314..0132ed13539 100644 --- a/scripts/generate_hardware_overview.py +++ b/scripts/generate_hardware_overview.py @@ -33,6 +33,7 @@ "HPE": "hardwares/hpe_logo.png", "Iluvatar CoreX": "hardwares/iluvatar_corex_logo.png", "FlagOS": "hardwares/flagos_logo.png", + "Enflame": "hardwares/enflame_logo.png", } OUTPUT = ROOT / "image/hardwares/supported_hardware.png" COLUMNS = 6