From aff72c2ea5d86dfb7eff7c2bf5bb3e91eb45df71 Mon Sep 17 00:00:00 2001 From: gatewayj <835269233@qq.com> Date: Sat, 21 Nov 2026 22:23:05 +0800 Subject: [PATCH 01/13] feat(phase-2): add a selectable NVIDIA cuObject RDMA backend --- crates/cli/src/commands/mod.rs | 29 ++- crates/core/src/data_transport.rs | 34 ++++ crates/core/src/lib.rs | 4 +- crates/s3/src/client.rs | 3 +- crates/s3/src/data_transport.rs | 27 ++- docs/ADR/0001-object-data-transport.md | 14 +- docs/rdma-build.md | 46 ++++- nixl/Cargo.lock | 61 ++++++- nixl/Cargo.toml | 5 + nixl/src/buffer.rs | 68 +++++++ nixl/src/main.rs | 23 ++- nixl/src/nvidia.rs | 69 ++++++++ nixl/src/pool.rs | 235 +++++++++++++++++-------- nixl/src/transport.rs | 9 +- nixl/src/transport/download.rs | 38 ++-- nixl/src/transport/tests.rs | 6 +- nixl/src/transport/upload.rs | 34 ++-- nixl/src/wire.rs | 6 +- nixl/src/wire/native_test.rs | 8 +- nixl/tests/interop.sh | 17 +- 20 files changed, 576 insertions(+), 160 deletions(-) create mode 100644 nixl/src/buffer.rs create mode 100644 nixl/src/nvidia.rs diff --git a/crates/cli/src/commands/mod.rs b/crates/cli/src/commands/mod.rs index 982142c5..7f2cab8d 100644 --- a/crates/cli/src/commands/mod.rs +++ b/crates/cli/src/commands/mod.rs @@ -9,8 +9,8 @@ use std::io::{IsTerminal, stderr, stdout}; use clap::{Parser, Subcommand, ValueEnum}; use rc_core::config::Defaults; use rc_core::{ - ConfigManager, DataTransportMode, RequestHeader, set_global_data_transport_mode, - set_global_request_headers, + ConfigManager, DataTransportMode, RdmaBackend, RequestHeader, set_global_data_transport_mode, + set_global_rdma_backend, set_global_request_headers, }; use crate::exit_code::ExitCode; @@ -98,6 +98,10 @@ pub struct Cli { #[arg(long, global = true, env = "RC_DATA_TRANSPORT", default_value = "http")] pub data_transport: DataTransportMode, + /// RDMA backend for auto or rdma mode: nixl or cuobject + #[arg(long, global = true, env = "RC_RDMA_BACKEND", default_value = "nixl")] + pub rdma_backend: RdmaBackend, + /// Maximum multipart parts per object for the destination backend #[arg(long, global = true, env = "RC_MAX_PARTS", default_value_t = 10_000, value_parser = clap::value_parser!(u32).range(1..=10_000))] @@ -371,6 +375,7 @@ pub enum Commands { /// Execute the CLI command and return an exit code pub async fn execute(cli: Cli) -> ExitCode { set_global_data_transport_mode(cli.data_transport); + set_global_rdma_backend(cli.rdma_backend); set_global_request_headers(cli.request_headers.clone()); let cli_output_options = GlobalOutputOptions::from_cli(&cli); if let Err(error) = rc_core::set_global_multipart_max_parts(cli.max_parts as usize) { @@ -592,6 +597,26 @@ mod tests { assert_eq!(cli.data_transport, DataTransportMode::Rdma); assert!(Cli::try_parse_from(["rc", "--data-transport", "udp", "alias", "list"]).is_err()); } + #[test] + fn rdma_backend_is_independent_of_fallback_policy() { + for policy in ["rdma", "auto"] { + let args = [ + "rc", + "--data-transport", + policy, + "--rdma-backend", + "cuobject", + "alias", + "list", + ]; + let cli = Cli::try_parse_from(args).expect("select NVIDIA cuObject"); + assert_eq!(cli.rdma_backend, RdmaBackend::CuObject); + assert_eq!(cli.data_transport, policy.parse().unwrap()); + } + let default = Cli::try_parse_from(["rc", "alias", "list"]).unwrap(); + assert_eq!(default.rdma_backend, RdmaBackend::Nixl); + assert!(Cli::try_parse_from(["rc", "--rdma-backend", "unknown", "alias", "list"]).is_err()); + } use clap::Parser; #[test] diff --git a/crates/core/src/data_transport.rs b/crates/core/src/data_transport.rs index 5c6b2b23..2a61da49 100644 --- a/crates/core/src/data_transport.rs +++ b/crates/core/src/data_transport.rs @@ -29,6 +29,40 @@ impl FromStr for DataTransportMode { } } +/// The wire protocol for external object transfers, independent of HTTP fallback. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +#[repr(u8)] +pub enum RdmaBackend { + #[default] + Nixl, + CuObject, +} + +impl FromStr for RdmaBackend { + type Err = String; + + fn from_str(value: &str) -> Result { + match value { + "nixl" => Ok(Self::Nixl), + "cuobject" => Ok(Self::CuObject), + _ => Err("RDMA backend must be nixl or cuobject".into()), + } + } +} + +static GLOBAL_BACKEND: AtomicU8 = AtomicU8::new(RdmaBackend::Nixl as u8); + +pub fn set_global_rdma_backend(backend: RdmaBackend) { + GLOBAL_BACKEND.store(backend as u8, Ordering::Relaxed); +} + +pub fn global_rdma_backend() -> RdmaBackend { + match GLOBAL_BACKEND.load(Ordering::Relaxed) { + i if i == RdmaBackend::CuObject as u8 => RdmaBackend::CuObject, + _ => RdmaBackend::Nixl, + } +} + /// Business outcome classification. Transport timeouts never imply rejection. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum DataTransferState { diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index 0ad149b6..6a61ad58 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -39,8 +39,8 @@ pub use alias::{ pub use config::{Config, ConfigManager}; pub use cors::{CorsConfiguration, CorsRule}; pub use data_transport::{ - DataTransferState, DataTransportMode, global_data_transport_mode, - set_global_data_transport_mode, + DataTransferState, DataTransportMode, RdmaBackend, global_data_transport_mode, + global_rdma_backend, set_global_data_transport_mode, set_global_rdma_backend, }; pub use encryption::{BucketEncryption, ObjectEncryptionRequest}; pub use error::{Error, MultipartAbortStatus, Result}; diff --git a/crates/s3/src/client.rs b/crates/s3/src/client.rs index 61d6264d..bb837118 100644 --- a/crates/s3/src/client.rs +++ b/crates/s3/src/client.rs @@ -1926,7 +1926,8 @@ impl S3Client { (_, Some(transport)) => Ok(Some(transport)), (DataTransportMode::Rdma, None) => Err(Error::DataTransfer { state: rc_core::DataTransferState::NotAccepted, - message: "This executable has no external object data provider".to_string(), + message: "This executable has no provider for the selected RDMA backend" + .to_string(), source: None, }), } diff --git a/crates/s3/src/data_transport.rs b/crates/s3/src/data_transport.rs index 2dd3ff59..81350e56 100644 --- a/crates/s3/src/data_transport.rs +++ b/crates/s3/src/data_transport.rs @@ -46,19 +46,38 @@ pub trait ObjectDataTransportFactory: Send + Sync { fn create(&self, control: Arc) -> Result>; } -static FACTORY: OnceLock> = OnceLock::new(); +static NIXL_FACTORY: OnceLock> = OnceLock::new(); -/// Install a provider before running the CLI. Replacing a provider is rejected. +static CUOBJECT_FACTORY: OnceLock> = OnceLock::new(); + +fn factory_slot( + backend: rc_core::RdmaBackend, +) -> &'static OnceLock> { + match backend { + rc_core::RdmaBackend::Nixl => &NIXL_FACTORY, + rc_core::RdmaBackend::CuObject => &CUOBJECT_FACTORY, + } +} + +/// Install the default NIXL provider before running the CLI. Replacing a provider is rejected. pub fn install_object_data_transport_factory( factory: Arc, ) -> Result<()> { - FACTORY.set(factory).map_err(|_| { + install_rdma_backend(rc_core::RdmaBackend::Nixl, factory) +} + +/// Register one backend without replacing another provider. +pub fn install_rdma_backend( + backend: rc_core::RdmaBackend, + factory: Arc, +) -> Result<()> { + factory_slot(backend).set(factory).map_err(|_| { Error::Config("An object data transport factory is already installed".to_string()) }) } pub(crate) fn installed_factory() -> Option> { - FACTORY.get().cloned() + factory_slot(rc_core::global_rdma_backend()).get().cloned() } /// A GET's S3 selection and an independent finite receive bound. diff --git a/docs/ADR/0001-object-data-transport.md b/docs/ADR/0001-object-data-transport.md index 6f9955ab..8f7d3e6b 100644 --- a/docs/ADR/0001-object-data-transport.md +++ b/docs/ADR/0001-object-data-transport.md @@ -8,13 +8,19 @@ completion, and abort continue to use the established S3 implementation. `rc-core` owns transport selection and business outcome classification. `rc-s3::data_transport` owns the optional provider ports, expressed with existing S3 read/write options, registered file transfers, and borrowed asynchronous IO. -The Linux NIXL executable installs an `ObjectDataTransportFactory` before -calling `rustfs_cli::run()`. +The Linux native executable registers an `ObjectDataTransportFactory` for +each compiled RDMA backend before calling `rustfs_cli::run()`. Backend +selection (`--rdma-backend nixl|cuobject`) and fallback policy are independent. +Both backends use the same multipart publication, version selection, file IO, +checksum verification and receipt handling. The common launcher preserves command dispatch, output, exit codes, and the existing worker-thread configuration. -The provider supplies NIXL agent metadata and a registered buffer description -to a host-owned `ControlExecutor`. The S3 client signs and sends a bodyless +The NIXL backend supplies agent metadata and a registered buffer description. +The NVIDIA cuObject backend supplies a direction-specific SDK token for the +registered host buffer. Each token stays alive with its buffer until a +receipt confirms completion. An uncertain transfer retains both resources +within the process registration budget. Both use the host-owned `ControlExecutor`. The S3 client signs and sends a bodyless HTTPS request on the shared S3 HTTP client using the alias timeout policy. It returns the status and headers directly, including duplicate headers. The provider verifies the RustFS transfer receipt and byte count. Credentials, endpoint addressing, custom headers, and TLS diff --git a/docs/rdma-build.md b/docs/rdma-build.md index c5dc1875..e347a351 100644 --- a/docs/rdma-build.md +++ b/docs/rdma-build.md @@ -1,6 +1,6 @@ # Object data over RDMA -## RustFS native NIXL/UCX +## Build the native client Build on Linux with Rust 1.99 or later, libclang, a C++ compiler and the NIXL libraries, headers and UCX plugin used by the RustFS server. Set @@ -27,6 +27,34 @@ feature and `RUSTFS_NIXL_ENABLE=true`. For a private CA, pass or `rdma` to reuse the selection across commands. The default is `http`. Signed control requests use the alias connection and read timeouts, including the wait for each transfer receipt. +### Choose the RDMA backend + +The native executable uses NIXL/UCX by default. To add NVIDIA cuObject +to the same executable, install the NVIDIA cuObject **client** SDK, +cuFile development libraries, libibverbs development headers and CUDA headers +for the target architecture. +Set `CUOBJCLIENT_ROOT` to the SDK prefix and `CUDA_HOME` to the CUDA toolkit. +The SDK's `libcuobjclient`, `libcufile` and RDMA plugin must be available +at runtime. Set `CUOBJ_ENV_PATH_JSON` to the NVIDIA client configuration +that selects the application RDMA device. + +```sh +./scripts/build-rdma.sh --release --features cuobject +rc --data-transport rdma --rdma-backend cuobject put model.bin lab/models/model.bin +rc --data-transport rdma --rdma-backend cuobject get lab/models/model.bin downloaded.bin +cmp model.bin downloaded.bin +rc --data-transport rdma --rdma-backend nixl get other/models/model.bin from-nixl.bin +``` + +Configure `lab` as a verified HTTPS alias for a RustFS server built with +`--features cuobject` and `RUSTFS_CUOBJECT_ENABLE=true`. Use an alias for a +NIXL-enabled server with the `nixl` backend. `RC_RDMA_BACKEND` sets the +backend for subsequent commands. The `rdma` policy requires the selected +backend. The `auto` policy allows a safe S3 fallback when that backend is +unavailable. The default `http` policy transfers the payload through S3. + +### Object transfers + File uploads use positional reads directly into two reusable registered windows. Each completed part frees a window for the next part, and S3 receives the completion list in part-number order. For transfers of up to 1 MiB, the client can register two 1 MiB @@ -53,6 +81,16 @@ size above 64 MiB use HTTP in `auto` and report an error in `rdma`. To run the real two-agent memory transfer test, use `cargo test --manifest-path nixl/Cargo.toml --locked`. For an S3 command round trip, set `RC` to the native executable and supply disposable buckets -in `NIXL_BUCKET` and `HTTP_BUCKET` on enabled and disabled endpoints. Run -`nixl/tests/interop.sh` with those variables. `UCX_TLS=tcp,self` exercises -the protocol on a machine without an RDMA network adapter. +in `RDMA_BUCKET` and `HTTP_BUCKET` on a native and an HTTP-only endpoint. +Run `RC_RDMA_BACKEND=cuobject nixl/tests/interop.sh` on an NVIDIA client +or `RC_RDMA_BACKEND=nixl nixl/tests/interop.sh` on a NIXL client. The +script accepts `NIXL_BUCKET` as an alias for `RDMA_BUCKET`. For NIXL, +`UCX_TLS=tcp,self` exercises the protocol on a machine without an RDMA adapter. + +On a cuObject client with an active RDMA device, run the buffer lifetime +test with the same SDK and device configuration used by the CLI: + +```sh +cargo test --locked --manifest-path nixl/Cargo.toml --features cuobject \ + cuobject_token_survives_cancellation_and_timeout -- --ignored +``` diff --git a/nixl/Cargo.lock b/nixl/Cargo.lock index 7e41930a..7eacb986 100644 --- a/nixl/Cargo.lock +++ b/nixl/Cargo.lock @@ -681,7 +681,7 @@ dependencies = [ "clang-sys", "itertools", "log", - "prettyplease", + "prettyplease 0.2.37", "proc-macro2", "quote", "regex", @@ -690,6 +690,24 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "bindgen" +version = "0.73.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "787ef8ef523575546b106a58213d6e6b06198a05c2f757258c68a74273670cfa" +dependencies = [ + "bitflags", + "cexpr", + "clang-sys", + "prettyplease 0.3.0", + "proc-macro2", + "quote", + "regex", + "rustc-hash", + "shlex 2.0.1", + "syn 3.0.10", +] + [[package]] name = "bitflags" version = "2.13.2" @@ -1038,6 +1056,27 @@ dependencies = [ "cmov", ] +[[package]] +name = "cuobject" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "486fec9045f8057131bf4bba71fbb87bf9dd3e44f853622cf7fa42713f3a108c" +dependencies = [ + "cuobject-sys", + "memmap2", + "thiserror", +] + +[[package]] +name = "cuobject-sys" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edc615b2a037eb0d80180d202f809629155742db9c9e94b9f7696b1100a7d52f" +dependencies = [ + "bindgen 0.73.2", + "cc", +] + [[package]] name = "darling" version = "0.23.0" @@ -2033,7 +2072,7 @@ version = "1.6.0" source = "git+https://github.com/houseme/nixl?rev=cc636c83f13d692e85b67e55aed092413d16fb41#cc636c83f13d692e85b67e55aed092413d16fb41" dependencies = [ "anyhow", - "bindgen", + "bindgen 0.71.1", "cc", "libc", "os_info", @@ -2504,6 +2543,16 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "prettyplease" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" +dependencies = [ + "proc-macro2", + "syn 3.0.10", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -2916,12 +2965,14 @@ version = "0.1.0" dependencies = [ "async-trait", "base64 0.22.1", + "cuobject", "getrandom 0.4.3", "http", "rc-core", "rc-s3", "rustfs-cli", "rustfs-nixl", + "self_cell", "tokio", ] @@ -3061,6 +3112,12 @@ dependencies = [ "libc", ] +[[package]] +name = "self_cell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813" + [[package]] name = "semver" version = "1.0.28" diff --git a/nixl/Cargo.toml b/nixl/Cargo.toml index 15d62978..1e5b4792 100644 --- a/nixl/Cargo.toml +++ b/nixl/Cargo.toml @@ -13,7 +13,12 @@ resolver = "3" name = "rc" path = "src/main.rs" +[features] +cuobject = ["dep:cuobject", "dep:self_cell"] + [dependencies] +cuobject = { version = "0.1.0", default-features = false, features = ["client"], optional = true } +self_cell = { version = "1.2", optional = true } rustfs-cli = { path = "../crates/cli" } rc-core = { path = "../crates/core" } rc-s3 = { path = "../crates/s3" } diff --git a/nixl/src/buffer.rs b/nixl/src/buffer.rs new file mode 100644 index 00000000..120676f9 --- /dev/null +++ b/nixl/src/buffer.rs @@ -0,0 +1,68 @@ +//! Backend registrations used by the shared object transfer pipeline. + +use base64::{Engine, engine::general_purpose::STANDARD}; +use http::HeaderValue; +use rc_core::{Error, RdmaBackend, Result}; +use rustfs_nixl::{NixlConfig, NixlServer, StagingChunk}; + +pub(super) enum Buffer { + Nixl { + chunk: StagingChunk, + agent: HeaderValue, + metadata: HeaderValue, + }, + #[cfg(feature = "cuobject")] + CuObject(crate::nvidia::HostBuffer), +} + +pub(super) fn register(backend: RdmaBackend, size: usize, count: usize) -> Result> { + if backend == RdmaBackend::CuObject { + #[cfg(feature = "cuobject")] + return crate::nvidia::register(size, count); + #[cfg(not(feature = "cuobject"))] + return Err(Error::UnsupportedFeature( + "The cuObject backend is not installed".into(), + )); + } + let id = getrandom::u64() + .map_err(|_| Error::General("Could not generate a NIXL agent ID".into()))?; + let name = format!("rc-{}-{id:016x}", std::process::id()); + let agent = NixlServer::new(&NixlConfig { + agent_name: name.clone(), + chunk_bytes: size, + pool_bytes: count * size, + ..NixlConfig::default() + }) + .map_err(nixl_error)?; + let mut metadata = + HeaderValue::from_str(&STANDARD.encode(agent.local_metadata().map_err(nixl_error)?)) + .map_err(|_| Error::General("Invalid NIXL agent metadata".into()))?; + metadata.set_sensitive(true); + let name = HeaderValue::from_str(&name).expect("ASCII agent ID"); + (0..count) + .map(|_| { + let chunk = agent.try_reserve().ok_or_else(|| { + Error::General("NIXL registration has no available window".into()) + })?; + Ok(Buffer::Nixl { + chunk, + agent: name.clone(), + metadata: metadata.clone(), + }) + }) + .collect() +} + +fn nixl_error(error: rustfs_nixl::NixlError) -> Error { + Error::General(format!("NIXL/UCX: {error}")) +} + +impl Buffer { + pub(super) fn writable(&mut self) -> Result<&mut [u8]> { + match self { + Self::Nixl { chunk, .. } => chunk.spare_mut().map_err(nixl_error), + #[cfg(feature = "cuobject")] + Self::CuObject(buffer) => buffer.writable(), + } + } +} diff --git a/nixl/src/main.rs b/nixl/src/main.rs index 521db613..37800f04 100644 --- a/nixl/src/main.rs +++ b/nixl/src/main.rs @@ -1,16 +1,27 @@ -//! rc with the RustFS native S3-over-NIXL/UCX transport. -#![forbid(unsafe_code)] +//! rc with native S3-over-RDMA providers. +#![deny(unsafe_code)] +#![cfg_attr(not(feature = "cuobject"), forbid(unsafe_code))] +mod buffer; +#[cfg(feature = "cuobject")] +mod nvidia; mod pool; mod transport; mod wire; -fn main() { - if let Err(error) = rc_s3::data_transport::install_object_data_transport_factory( - std::sync::Arc::new(transport::Factory), - ) { +use rc_core::RdmaBackend; + +fn register(backend: RdmaBackend) { + let factory = std::sync::Arc::new(transport::Factory(backend)); + if let Err(error) = rc_s3::data_transport::install_rdma_backend(backend, factory) { eprintln!("{error}"); std::process::exit(error.exit_code()); } +} + +fn main() { + register(RdmaBackend::Nixl); + #[cfg(feature = "cuobject")] + register(RdmaBackend::CuObject); rustfs_cli::run(); } diff --git a/nixl/src/nvidia.rs b/nixl/src/nvidia.rs new file mode 100644 index 00000000..9dc08dae --- /dev/null +++ b/nixl/src/nvidia.rs @@ -0,0 +1,69 @@ +//! NVIDIA DC token ownership and registered host memory. + +use crate::buffer::Buffer; +use crate::pool::Window; +use cuobject::{Client, ClientBuffer, ClientToken, Operation}; +use http::{HeaderMap, HeaderValue, Method}; +use rc_core::{Error, Result}; +use std::sync::Arc; + +fn sdk_error(error: cuobject::Error) -> Error { + Error::General(format!("NVIDIA cuObject: {error}")) +} + +pub(super) fn register(size: usize, count: usize) -> Result> { + let client = Arc::new(Client::new().map_err(sdk_error)?); + (0..count) + .map(|_| { + let buffer = ClientBuffer::new(client.clone(), size).map_err(sdk_error)?; + Ok(Buffer::CuObject(HostBuffer(buffer))) + }) + .collect() +} + +pub(super) struct HostBuffer(ClientBuffer>); + +type Token<'a> = ClientToken<'a, Arc>; + +// Dropping the token releases its SDK QP reference. Keep it with the memory +// registration through cancellation, timeout, and any unconfirmed receipt. +self_cell::self_cell!( + pub(crate) struct Exposure { + owner: Window, + #[covariant] + dependent: Token, + } +); + +impl HostBuffer { + #[expect( + unsafe_code, + reason = "the SDK exposes registered host memory through raw slices" + )] + pub(super) fn writable(&mut self) -> Result<&mut [u8]> { + // SAFETY: ClientBuffer::new owns this entire host mapping. A Window + // gives the caller exclusive access. Exposing it moves the Window + // and keeps the token alive until the peer confirms completion or + // declines the transfer. An uncertain transfer is never reissued. + unsafe { self.0.slice_mut(0, self.0.len()) }.map_err(sdk_error) + } + + pub(super) fn describe( + &self, + method: &Method, + len: usize, + headers: &mut HeaderMap, + ) -> Result> { + let operation = match *method { + Method::GET => Operation::Get, + Method::PUT => Operation::Put, + _ => return Err(Error::General("Unsupported cuObject operation".into())), + }; + let token = self.0.token(0, len, operation).map_err(sdk_error)?; + let mut value = HeaderValue::from_str(token.as_str()) + .map_err(|_| Error::General("Invalid NVIDIA cuObject token".into()))?; + value.set_sensitive(true); + headers.insert(cuobject::TOKEN_HEADER, value); + Ok(token) + } +} diff --git a/nixl/src/pool.rs b/nixl/src/pool.rs index e5d0ba01..60d0e177 100644 --- a/nixl/src/pool.rs +++ b/nixl/src/pool.rs @@ -1,28 +1,32 @@ -//! Registered host memory and ownership while the server can access it. +//! Bounded registration and exclusive ownership until a transfer completes. -use base64::{Engine, engine::general_purpose::STANDARD}; -use http::{HeaderMap, HeaderValue}; -use rc_core::{Error, Result}; -use rustfs_nixl::{NixlConfig, NixlServer, StagingChunk}; +use crate::buffer::{self, Buffer}; +use http::{HeaderMap, Method}; +use rc_core::{Error, RdmaBackend, Result}; use std::sync::{Arc, Mutex}; use std::time::Duration; use tokio::sync::{Mutex as AsyncMutex, Semaphore, SemaphorePermit, watch}; pub(crate) const WINDOW: usize = rc_s3::multipart::DEFAULT_PART_SIZE as usize; -pub(crate) const SMALL_WINDOW: usize = 1024 * 1024; -// Two windows allow the next network read to overlap the previous file write. -static AGENTS: Semaphore = Semaphore::const_new(8); -static QUARANTINE: Mutex> = Mutex::new(Vec::new()); +const SMALL_WINDOW: usize = 1024 * 1024; const WINDOWS_PER_POOL: usize = 2; +static AGENTS: Semaphore = Semaphore::const_new(8); +static QUARANTINE: Mutex> = Mutex::new(Vec::new()); -/// One active registration per S3 client. A larger request upgrades the pool; -/// outstanding windows keep their original registration alive. #[derive(Default)] pub(crate) struct Pools { + backend: RdmaBackend, active: AsyncMutex>>, } impl Pools { + pub(crate) fn new(backend: RdmaBackend) -> Self { + Self { + backend, + active: AsyncMutex::default(), + } + } + pub(crate) async fn reserve(&self, required: u64) -> Result { let size = if required <= SMALL_WINDOW as u64 { SMALL_WINDOW @@ -33,15 +37,16 @@ impl Pools { let pool = { let mut active = self.active.lock().await; if let Some(pool) = active.as_ref() - && pool.agent.chunk_bytes() >= size + && pool.size >= size && *pool.lost.borrow() < WINDOWS_PER_POOL { pool.clone() } else { - let pool = tokio::task::spawn_blocking(move || Pool::open(size)) + let backend = self.backend; + let pool = tokio::task::spawn_blocking(move || Pool::open(backend, size)) .await .map_err(|_| { - Error::General("NIXL agent startup was interrupted".into()) + Error::General("RDMA registration was interrupted".into()) })??; *active = Some(pool.clone()); pool @@ -55,97 +60,154 @@ impl Pools { } struct Pool { + size: usize, + free: Mutex>, + available: Semaphore, lost: watch::Sender, - agent: Arc, - name: HeaderValue, - metadata: HeaderValue, _budget: SemaphorePermit<'static>, } impl Pool { - fn open(window: usize) -> Result> { + fn open(backend: RdmaBackend, size: usize) -> Result> { let budget = AGENTS .try_acquire() - .map_err(|_| Error::General("NIXL registered memory budget exhausted".into()))?; - let id = getrandom::u64() - .map_err(|_| Error::General("Could not generate a NIXL agent ID".into()))?; - let name = format!("rc-{}-{id:016x}", std::process::id()); - let agent = NixlServer::new(&NixlConfig { - agent_name: name.clone(), - chunk_bytes: window, - pool_bytes: WINDOWS_PER_POOL * window, - ..NixlConfig::default() - }) - .map_err(native_error)?; - let mut metadata = - HeaderValue::from_str(&STANDARD.encode(agent.local_metadata().map_err(native_error)?)) - .map_err(|_| Error::General("Invalid NIXL agent metadata".into()))?; - metadata.set_sensitive(true); + .map_err(|_| Error::General("RDMA registered memory budget exhausted".into()))?; + let buffers = buffer::register(backend, size, WINDOWS_PER_POOL)?; Ok(Arc::new(Self { - agent, - name: HeaderValue::from_str(&name).expect("ASCII agent ID"), - metadata, + size, + free: Mutex::new(buffers), + available: Semaphore::new(WINDOWS_PER_POOL), lost: watch::Sender::new(0), _budget: budget, })) } - /// A retired registration wakes its waiters so the owner can replace it. async fn reserve(self: &Arc) -> Result> { let mut lost = self.lost.subscribe(); tokio::select! { biased; _ = lost.wait_for(|count| *count == WINDOWS_PER_POOL) => Ok(None), - result = self.agent.reserve(Duration::from_secs(60)) => { - Ok(Some(Window { chunk: result.map_err(native_error)?, pool: self.clone() })) + result = tokio::time::timeout(Duration::from_secs(60), self.available.acquire()) => { + let permit = result + .map_err(|_| Error::General("Timed out waiting for a registered window".into()))? + .expect("registration semaphore remains open"); + let buffer = self.free.lock().unwrap_or_else(|e| e.into_inner()) + .pop().expect("each permit owns a free window"); + permit.forget(); + Ok(Some(Window { buffer: Some(buffer), pool: self.clone(), len: 0 })) } } } } -pub(crate) fn native_error(error: rustfs_nixl::NixlError) -> Error { - Error::General(format!("NIXL/UCX: {error}")) -} - pub(crate) struct Window { - pub(crate) chunk: StagingChunk, + buffer: Option, pool: Arc, + len: usize, } - impl Window { - pub(crate) fn bind(&self, headers: &mut HeaderMap, len: usize) -> Result<()> { - crate::wire::bind( - headers, - &self.pool.name, - &self.pool.metadata, - self.chunk.addr(), - len, - ) + pub(crate) fn writable(&mut self) -> Result<&mut [u8]> { + self.buffer.as_mut().expect("owned window").writable() + } + pub(crate) fn received(&mut self) -> Result<&[u8]> { + let len = self.len; + self.writable()? + .get(..len) + .ok_or_else(|| Error::General("Received length exceeds the registered window".into())) } - pub(crate) fn expose(self) -> Exposed { - Exposed(Some(self)) + pub(crate) fn finish_read(&mut self, len: usize) -> Result<()> { + if len > self.pool.size { + return Err(Error::General( + "Received length exceeds the registered window".into(), + )); + } + self.len = len; + Ok(()) + } + + pub(crate) fn len(&self) -> usize { + self.len + } + pub(crate) fn expose( + self, + _method: &Method, + len: usize, + headers: &mut HeaderMap, + ) -> Result { + let transfer = match self.buffer.as_ref().expect("owned window") { + Buffer::Nixl { + chunk, + agent, + metadata, + } => { + crate::wire::bind(headers, agent, metadata, chunk.addr(), len)?; + Transfer::Nixl(self) + } + #[cfg(feature = "cuobject")] + Buffer::CuObject(_) => { + Transfer::CuObject(crate::nvidia::Exposure::try_new(self, |window| { + let Some(Buffer::CuObject(buffer)) = window.buffer.as_ref() else { + unreachable!("cuObject window") + }; + buffer.describe(_method, len, headers) + })?) + } + }; + Ok(Exposed(Some(transfer))) } } -/// Until a receipt proves completion, cancellation must retain the address -/// and its registration. The process registration budget also covers this list. -pub(crate) struct Exposed(Option); +impl Drop for Window { + fn drop(&mut self) { + if let Some(buffer) = self.buffer.take() { + self.pool + .free + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(buffer); + self.pool.available.add_permits(1); + } + } +} + +enum Transfer { + Nixl(Window), + #[cfg(feature = "cuobject")] + CuObject(crate::nvidia::Exposure), +} + +impl Transfer { + fn window(&self) -> &Window { + match self { + Self::Nixl(window) => window, + #[cfg(feature = "cuobject")] + Self::CuObject(transfer) => transfer.borrow_owner(), + } + } + fn finished(self) -> Window { + match self { + Self::Nixl(window) => window, + #[cfg(feature = "cuobject")] + Self::CuObject(transfer) => transfer.into_owner(), + } + } +} +pub(crate) struct Exposed(Option); impl Exposed { pub(crate) fn finished(mut self) -> Window { - self.0.take().expect("owned NIXL window") + self.0.take().expect("owned transfer").finished() } } - impl Drop for Exposed { fn drop(&mut self) { - if let Some(window) = self.0.take() { - window.pool.lost.send_modify(|lost| *lost += 1); + if let Some(transfer) = self.0.take() { + transfer.window().pool.lost.send_modify(|lost| *lost += 1); QUARANTINE .lock() - .unwrap_or_else(|err| err.into_inner()) - .push(window); + .unwrap_or_else(|e| e.into_inner()) + .push(transfer); } } } @@ -156,7 +218,18 @@ mod tests { #[tokio::test] async fn uncertain_windows_wake_waiters_and_cannot_be_reissued() { - let pools = Pools::default(); + check_window_lifetime(RdmaBackend::Nixl).await; + } + + #[cfg(feature = "cuobject")] + #[tokio::test] + #[ignore = "requires an NVIDIA cuObject client SDK and an active RDMA device"] + async fn cuobject_token_survives_cancellation_and_timeout() { + check_window_lifetime(RdmaBackend::CuObject).await; + } + + async fn check_window_lifetime(backend: RdmaBackend) { + let pools = Pools::new(backend); let first = pools.reserve(32).await.unwrap(); let second = pools.reserve(32).await.unwrap(); let old = first.pool.clone(); @@ -168,8 +241,27 @@ mod tests { _ = &mut waiting => panic!("both windows are checked out"), _ = std::future::ready(()) => {} } - drop(first.expose()); - drop(second.expose()); + let mut headers = HeaderMap::new(); + let first = first.expose(&Method::GET, 32, &mut headers).unwrap(); + #[cfg(feature = "cuobject")] + if backend == RdmaBackend::CuObject { + assert!(headers[cuobject::TOKEN_HEADER].is_sensitive()); + } + let exchanging = |exposed: Exposed| async move { + std::future::pending::<()>().await; + exposed.finished() + }; + let cancelled = tokio::spawn(exchanging(first)); + cancelled.abort(); + assert!(matches!(cancelled.await, Err(e) if e.is_cancelled())); + let second = second + .expose(&Method::PUT, 32, &mut HeaderMap::new()) + .unwrap(); + assert!( + tokio::time::timeout(Duration::from_millis(1), exchanging(second)) + .await + .is_err() + ); tokio::select! { biased; result = waiting => assert!(result.unwrap().is_none()), @@ -177,8 +269,13 @@ mod tests { } let replacement = pools.reserve(32).await.unwrap(); assert!(!Arc::ptr_eq(&old, &replacement.pool)); - let returned = replacement.expose().finished(); + let fresh_pool = replacement.pool.clone(); + let returned = replacement + .expose(&Method::GET, 32, &mut HeaderMap::new()) + .unwrap() + .finished(); drop(returned); - assert!(old.agent.try_reserve().is_none()); + assert_eq!(fresh_pool.available.available_permits(), WINDOWS_PER_POOL); + assert_eq!(old.available.available_permits(), 0); } } diff --git a/nixl/src/transport.rs b/nixl/src/transport.rs index 2033f831..952e0a39 100644 --- a/nixl/src/transport.rs +++ b/nixl/src/transport.rs @@ -11,16 +11,17 @@ use rustfs_nixl::RDMA_REPLY_HEADER; use std::sync::Arc; use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; -use crate::pool::{Exposed, Pools, WINDOW, Window, native_error}; +use crate::pool::{Exposed, Pools, WINDOW, Window}; use crate::wire; +use rc_core::RdmaBackend; -pub(crate) struct Factory; +pub(crate) struct Factory(pub(crate) RdmaBackend); impl ObjectDataTransportFactory for Factory { fn create(&self, control: Arc) -> Result> { Ok(Arc::new(Transport { control, - pools: Pools::default(), + pools: Pools::new(self.0), })) } } @@ -33,7 +34,7 @@ struct Transport { fn failed(state: DataTransferState, source: Error) -> DataTransportError { DataTransportError { state, - message: "RustFS NIXL object transfer".into(), + message: "RDMA object transfer".into(), source: Some(Box::new(source)), } } diff --git a/nixl/src/transport/download.rs b/nixl/src/transport/download.rs index abb1d545..e1b38423 100644 --- a/nixl/src/transport/download.rs +++ b/nixl/src/transport/download.rs @@ -48,8 +48,9 @@ impl Transport { }; let window = self.pools.reserve(len as u64).await.map_err(unavailable)?; // An empty object still requires a nonempty descriptor. - window.bind(&mut headers, len.max(1)).map_err(unavailable)?; - let exposed = window.expose(); + let exposed = window + .expose(&Method::GET, len.max(1), &mut headers) + .map_err(unavailable)?; let (response, exposed) = self .exchange( read_request( @@ -76,7 +77,7 @@ impl Transport { } if response.status != expected { return Err(rejected(Error::General( - "Unexpected NIXL GET status".into(), + "Unexpected RDMA GET status".into(), ))); } wire::receipt(expected, &response.headers, len as u64).map_err(rejected)?; @@ -86,7 +87,7 @@ impl Transport { .is_some_and(|value| value != "0") { return Err(rejected(Error::General( - "NIXL GET returned an HTTP payload".into(), + "RDMA GET returned an HTTP payload".into(), ))); } if wire::field(&response.headers, "x-amz-version-id").map_err(rejected)? @@ -107,15 +108,11 @@ impl Transport { != Some(&expected_range) { return Err(rejected(Error::General( - "NIXL GET returned a different object range".into(), + "RDMA GET returned a different object range".into(), ))); } } - window - .chunk - .advance(len) - .map_err(native_error) - .map_err(rejected)?; + window.finish_read(len).map_err(rejected)?; Ok(window) } @@ -126,7 +123,7 @@ impl Transport { ) -> DataTransportResult { if request.options.customer_key.is_some() { return Err(unavailable(Error::UnsupportedFeature( - "NIXL does not encrypt SSE-C payloads in transit".into(), + "RDMA does not encrypt SSE-C payloads in transit".into(), ))); } let requested_version = request.options.version_id.as_deref(); @@ -154,7 +151,7 @@ impl Transport { let length = request.max_bytes.unwrap_or(total).min(total); if length > request.max_receive_bytes { return Err(rejected(Error::General( - "NIXL object exceeds the receive bound".into(), + "RDMA object exceeds the receive bound".into(), ))); } let observed_version = wire::field(&head.headers, "x-amz-version-id").map_err(rejected)?; @@ -178,27 +175,20 @@ impl Transport { loop { let write = async { if length == total { - checksum.update(current.chunk.staged().map_err(native_error)?); + checksum.update(current.received()?); } - let offset = end - current.chunk.len() as u64; + let offset = end - current.len() as u64; match &mut target { - Sink::Writer(writer) => { - writer - .write_all(current.chunk.staged().map_err(native_error)?) - .await? - } + Sink::Writer(writer) => writer.write_all(current.received()?).await?, Sink::File(file) => { use std::os::unix::fs::FileExt; let file = file.clone(); tokio::task::spawn_blocking(move || { - file.write_all_at( - current.chunk.staged().map_err(native_error)?, - offset, - )?; + file.write_all_at(current.received()?, offset)?; Ok::<_, Error>(()) }) .await - .map_err(|_| Error::General("NIXL file write was interrupted".into()))??; + .map_err(|_| Error::General("RDMA file write was interrupted".into()))??; } } (request.on_progress)(end, Some(length)); diff --git a/nixl/src/transport/tests.rs b/nixl/src/transport/tests.rs index c561f803..6ef57cdc 100644 --- a/nixl/src/transport/tests.rs +++ b/nixl/src/transport/tests.rs @@ -36,7 +36,7 @@ async fn download( queries: Mutex::default(), get_version, }); - let transport = Factory.create(endpoint.clone()).unwrap(); + let transport = Factory(RdmaBackend::Nixl).create(endpoint.clone()).unwrap(); let path = RemotePath::new("test", "bucket", "key"); let options = rc_core::TransferReadOptions { version_id: version_id.map(str::to_owned), @@ -98,7 +98,9 @@ async fn a_delete_marker_keeps_its_version_and_exit_code() { } } - let transport = Factory.create(Arc::new(DeleteMarker)).unwrap(); + let transport = Factory(RdmaBackend::Nixl) + .create(Arc::new(DeleteMarker)) + .unwrap(); let path = RemotePath::new("test", "bucket", "key"); let options = rc_core::ObjectReadOptions { version_id: Some("v2".into()), diff --git a/nixl/src/transport/upload.rs b/nixl/src/transport/upload.rs index 9bff30d7..ed84a6f7 100644 --- a/nixl/src/transport/upload.rs +++ b/nixl/src/transport/upload.rs @@ -12,11 +12,7 @@ impl Transport { .reserve(request.content_length) .await .map_err(unavailable)?; - let dest = window - .chunk - .spare_mut() - .map_err(native_error) - .map_err(unavailable)?; + let dest = window.writable().map_err(unavailable)?; source .read_exact(&mut dest[..len]) .await @@ -30,7 +26,7 @@ impl Transport { != 0 { return Err(rejected(Error::Conflict( - "NIXL part source exceeds its declared length".into(), + "RDMA part source exceeds its declared length".into(), ))); } self.send_part(&request, window) @@ -41,7 +37,7 @@ impl Transport { fn declined_part() -> DataTransportError { rejected(Error::UnsupportedFeature( - "The endpoint did not accept the NIXL part".into(), + "The endpoint did not accept the RDMA part".into(), )) } @@ -51,7 +47,7 @@ fn part_len(request: &UploadRequest<'_>) -> DataTransportResult { .filter(|n| (1..=WINDOW).contains(n)) .ok_or_else(|| { unavailable(Error::UnsupportedFeature( - "Part exceeds the registered NIXL window".into(), + "Part exceeds the registered RDMA window".into(), )) }) } @@ -73,11 +69,7 @@ impl StagedUploadTransport for Transport { .reserve(first_part_bytes) .await .map_err(unavailable)?; - window - .chunk - .append(&[0]) - .map_err(native_error) - .map_err(unavailable)?; + window.writable().map_err(unavailable)?[0] = 0; let options = rc_core::ObjectWriteOptions::default(); let request = UploadRequest { path, @@ -106,14 +98,11 @@ impl StagedUploadTransport for Transport { .await .map_err(unavailable)?; let window = tokio::task::spawn_blocking(move || { - file.read_exact_at( - &mut window.chunk.spare_mut().map_err(native_error)?[..len], - offset, - )?; + file.read_exact_at(&mut window.writable()?[..len], offset)?; Ok::<_, Error>(window) }) .await - .map_err(|_| rejected(Error::General("NIXL file read was interrupted".into())))? + .map_err(|_| rejected(Error::General("RDMA file read was interrupted".into())))? .map_err(rejected)?; self.send_part(&request, window) .await? @@ -133,17 +122,18 @@ impl Transport { } = request.operation else { return Err(unavailable(Error::UnsupportedFeature( - "NIXL writes require an unpublished multipart part".into(), + "RDMA writes require an unpublished multipart part".into(), ))); }; let len = part_len(request)?; let mut headers = HeaderMap::new(); - window.bind(&mut headers, len).map_err(unavailable)?; + let exposed = window + .expose(&Method::PUT, len, &mut headers) + .map_err(unavailable)?; let query = vec![ ("uploadId".into(), upload_id.into()), ("partNumber".into(), part_number.to_string()), ]; - let exposed = window.expose(); let (response, exposed) = self .exchange( wire::request(Method::PUT, request.path, query, headers), @@ -163,7 +153,7 @@ impl Transport { let etag = wire::field(&response.headers, "etag") .map_err(rejected)? .filter(|e| !e.is_empty()) - .ok_or_else(|| rejected(Error::General("NIXL UploadPart returned no ETag".into())))?; + .ok_or_else(|| rejected(Error::General("RDMA UploadPart returned no ETag".into())))?; let mut object = ObjectInfo::file(&request.path.key, len as i64); object.etag = Some(etag.into()); Ok(Some(UploadResult { diff --git a/nixl/src/wire.rs b/nixl/src/wire.rs index c83ae964..44ad99eb 100644 --- a/nixl/src/wire.rs +++ b/nixl/src/wire.rs @@ -54,16 +54,16 @@ pub(crate) fn field<'a>(headers: &'a HeaderMap, name: &str) -> Result Result<()> { if field(headers, RDMA_REPLY_HEADER)? != Some(status.as_str()) { return Err(Error::UnsupportedFeature( - "The endpoint did not confirm a RustFS NIXL transfer".into(), + "The endpoint did not confirm an RDMA transfer".into(), )); } let moved = field(headers, RDMA_BYTES_TRANSFERRED_HEADER)? .unwrap_or("0") .parse::() - .map_err(|_| Error::General("Invalid NIXL transfer count".into()))?; + .map_err(|_| Error::General("Invalid RDMA transfer count".into()))?; if moved != bytes { return Err(Error::General(format!( - "NIXL transferred {moved} of {bytes} bytes" + "RDMA transferred {moved} of {bytes} bytes" ))); } Ok(()) diff --git a/nixl/src/wire/native_test.rs b/nixl/src/wire/native_test.rs index acc3c020..00576801 100644 --- a/nixl/src/wire/native_test.rs +++ b/nixl/src/wire/native_test.rs @@ -13,9 +13,9 @@ async fn rustfs_reads_and_writes_the_advertised_host_window() { }) .unwrap(); let mut source = client.reserve(6).await.unwrap(); - source.chunk.append(b"upload").unwrap(); + source.writable().unwrap()[..6].copy_from_slice(b"upload"); let mut fields = HeaderMap::new(); - source.bind(&mut fields, 6).unwrap(); + let exposed = source.expose(&Method::PUT, 6, &mut fields).unwrap(); let token = RdmaToken::from_headers( fields[NIXL_AGENT_HEADER].to_str().unwrap(), Some(fields[NIXL_METADATA_HEADER].to_str().unwrap()), @@ -36,5 +36,7 @@ async fn rustfs_reads_and_writes_the_advertised_host_window() { .await .unwrap(); assert_eq!(written, 6); - assert_eq!(source.chunk.staged().unwrap(), b"result"); + let mut source = exposed.finished(); + source.finish_read(6).unwrap(); + assert_eq!(source.received().unwrap(), b"result"); } diff --git a/nixl/tests/interop.sh b/nixl/tests/interop.sh index c67767aa..8230469f 100755 --- a/nixl/tests/interop.sh +++ b/nixl/tests/interop.sh @@ -1,9 +1,10 @@ #!/usr/bin/env bash # Run against disposable buckets on two verified HTTPS aliases. The second -# endpoint runs the same RustFS binary with RUSTFS_NIXL_ENABLE=false. +# endpoint serves ordinary S3. RC_RDMA_BACKEND selects the native protocol. set -euo pipefail : "${RC:?path to the native rc executable}" -: "${NIXL_BUCKET:?alias/bucket on the native endpoint}" +RDMA_BUCKET=${RDMA_BUCKET:-${NIXL_BUCKET:-}} +: "${RDMA_BUCKET:?alias/bucket on the native endpoint}" : "${HTTP_BUCKET:?alias/bucket on the HTTP-only endpoint}" tmp=$(mktemp -d) trap 'rm -rf "$tmp"' EXIT @@ -17,22 +18,22 @@ dd if=/dev/urandom of="$tmp/model" bs=1M count=129 status=none printf 'NIXL part receipt\n' > "$tmp/small" : > "$tmp/empty" for name in model small empty; do - object="$NIXL_BUCKET/$prefix/$name" + object="$RDMA_BUCKET/$prefix/$name" nr cp "$tmp/$name" "$object" nr cp "$object" "$tmp/native-$name" plain cp "$object" "$tmp/http-$name" cmp "$tmp/$name" "$tmp/native-$name" cmp "$tmp/$name" "$tmp/http-$name" done -nr object head --bytes 19 "$NIXL_BUCKET/$prefix/model" > "$tmp/range" +nr object head --bytes 19 "$RDMA_BUCKET/$prefix/model" > "$tmp/range" head -c 19 "$tmp/model" | cmp - "$tmp/range" -plain cp "$tmp/small" "$NIXL_BUCKET/$prefix/http-source" -nr cp "$NIXL_BUCKET/$prefix/http-source" "$tmp/from-http" +plain cp "$tmp/small" "$RDMA_BUCKET/$prefix/http-source" +nr cp "$RDMA_BUCKET/$prefix/http-source" "$tmp/from-http" cmp "$tmp/small" "$tmp/from-http" -automatic cp "$tmp/small" "$NIXL_BUCKET/$prefix/auto" -nr cp "$NIXL_BUCKET/$prefix/auto" "$tmp/auto" +automatic cp "$tmp/small" "$RDMA_BUCKET/$prefix/auto" +nr cp "$RDMA_BUCKET/$prefix/auto" "$tmp/auto" cmp "$tmp/small" "$tmp/auto" object="$HTTP_BUCKET/$prefix/declined" From c9d3164d004d1c161288a5e8f0377ae8d2bd320c Mon Sep 17 00:00:00 2001 From: gatewayj <835269233@qq.com> Date: Sat, 21 Nov 2026 23:19:18 +0800 Subject: [PATCH 02/13] fix(transfer): guard RDMA headers and reuse only confirmed windows --- .github/scripts/build-cuobject-client.sh | 31 +++++++ .github/workflows/nixl.yml | 5 +- crates/cli/src/commands/mod.rs | 31 +++++++ crates/core/src/alias.rs | 17 +++- crates/s3/src/client.rs | 47 ++++++++-- crates/s3/src/client/object_error.rs | 110 +++++++++++++++++++++++ crates/s3/src/data_transport.rs | 17 ++++ docs/rdma-build.md | 10 ++- nixl/src/nvidia.rs | 40 ++++++++- nixl/src/pool.rs | 68 ++++++++++++-- nixl/src/transport.rs | 8 +- nixl/src/transport/download.rs | 2 +- nixl/src/transport/tests.rs | 105 ++++++++++++++++++++++ nixl/src/transport/upload.rs | 2 +- 14 files changed, 464 insertions(+), 29 deletions(-) create mode 100755 .github/scripts/build-cuobject-client.sh diff --git a/.github/scripts/build-cuobject-client.sh b/.github/scripts/build-cuobject-client.sh new file mode 100755 index 00000000..a7b1cbc4 --- /dev/null +++ b/.github/scripts/build-cuobject-client.sh @@ -0,0 +1,31 @@ +#!/usr/bin/env bash +# Build and link the combined client against NVIDIA's x86_64 SDK without a GPU. +set -euo pipefail +: "${NIXL_PREFIX:?NIXL SDK prefix is required}" +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +packages="${RUNNER_TEMP:-$work}/cuobject-packages" +mkdir -p "$packages" +repo=https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2404/x86_64 +while read -r digest package; do + archive="$packages/$package" + if ! echo "$digest $archive" | sha256sum --check --status 2>/dev/null; then + curl --fail --silent --show-error --location --retry 3 --retry-all-errors \ + --connect-timeout 20 --max-time 300 "$repo/$package" -o "$archive" + echo "$digest $archive" | sha256sum --check + fi + dpkg-deb -x "$archive" "$work/sdk" +done <<'PACKAGES' +e06a0f89898ec9a7df3124e4d6ad3a1ebf92a0b3ea42c3f81c6fff5ef92a5126 libcuobjclient-13-5_1.4.0.107-1_amd64.deb +ce6188558d94a15593c4ae82cb578828ce7686ea09e2658a201962f56e66fe7c libcuobjclient-dev-13-5_1.4.0.107-1_amd64.deb +d02925a4ab1706b6ba578ff6d7db953c5bcae3291d3abdbd7e4311de8d3d4c11 libcufile-13-5_1.20.0.107-1_amd64.deb +b8e2c20dc796ca09b3ec55ce5fd72f2bdc4c6efea857b907a9cec5b356256072 libcufile-dev-13-5_1.20.0.107-1_amd64.deb +e079c64a1ab86d69a43a7dd8029ddcacb7de8c1953a4c095e485429bd90e8636 cuda-cudart-dev-13-5_13.5.37-1_amd64.deb +PACKAGES +export CUDA_HOME="$work/sdk/usr/local/cuda-13.5" +export CUOBJCLIENT_ROOT="$CUDA_HOME/targets/x86_64-linux" +export LD_LIBRARY_PATH="$CUOBJCLIENT_ROOT/lib:$NIXL_PREFIX/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" +export LIBRARY_PATH="$CUOBJCLIENT_ROOT/lib${LIBRARY_PATH:+:$LIBRARY_PATH}" +export NIXL_PLUGIN_DIR="$NIXL_PREFIX/lib/plugins" +./scripts/build-rdma.sh --features cuobject +cargo test --locked --manifest-path nixl/Cargo.toml --features cuobject diff --git a/.github/workflows/nixl.yml b/.github/workflows/nixl.yml index 0ab3fcf3..71e21b66 100644 --- a/.github/workflows/nixl.yml +++ b/.github/workflows/nixl.yml @@ -10,6 +10,7 @@ on: - 'Cargo.lock' - 'scripts/build-rdma.sh' - '.github/scripts/build-nixl-runtime.sh' + - '.github/scripts/build-cuobject-client.sh' - '.github/workflows/nixl.yml' permissions: @@ -35,7 +36,7 @@ jobs: run: | echo "NIXL_PREFIX=$RUNNER_TEMP/nixl" >> "$GITHUB_ENV" sudo apt-get update - sudo apt-get install -y --no-install-recommends libclang-dev ninja-build python3-dev python3-venv + sudo apt-get install -y --no-install-recommends libibverbs-dev librdmacm1t64 libclang-dev ninja-build python3-dev python3-venv python3 -m venv "$RUNNER_TEMP/native-tools" "$RUNNER_TEMP/native-tools/bin/pip" install meson==1.12.1 pybind11==3.1.0 echo "$RUNNER_TEMP/native-tools/bin" >> "$GITHUB_PATH" @@ -54,3 +55,5 @@ jobs: export NIXL_PLUGIN_DIR="$NIXL_PREFIX/lib/plugins" ./scripts/build-rdma.sh cargo test --locked --manifest-path nixl/Cargo.toml + - name: Build and test the NVIDIA cuObject client with the real SDK + run: .github/scripts/build-cuobject-client.sh diff --git a/crates/cli/src/commands/mod.rs b/crates/cli/src/commands/mod.rs index 7f2cab8d..57ca03f0 100644 --- a/crates/cli/src/commands/mod.rs +++ b/crates/cli/src/commands/mod.rs @@ -597,6 +597,37 @@ mod tests { assert_eq!(cli.data_transport, DataTransportMode::Rdma); assert!(Cli::try_parse_from(["rc", "--data-transport", "udp", "alias", "list"]).is_err()); } + #[test] + fn external_transport_headers_cannot_be_supplied_by_the_caller() { + for name in [ + "X-AmZ-RdMa-ToKeN", + "x-amz-rdma-reply", + "x-amz-rdma-bytes-transferred", + "x-rustfs-nixl-agent", + "x-rustfs-nixl-metadata", + "x-rustfs-nixl-buffer", + ] { + for mode in ["http", "auto", "rdma"] { + assert!( + Cli::try_parse_from([ + "rc", + "--data-transport", + mode, + "-H", + &format!("{name}:opaque"), + "alias", + "list" + ]) + .is_err(), + "{name} in {mode}" + ); + } + } + assert!( + Cli::try_parse_from(["rc", "-H", "x-amz-meta-format:onnx", "alias", "list"]).is_ok() + ); + } + #[test] fn rdma_backend_is_independent_of_fallback_policy() { for policy in ["rdma", "auto"] { diff --git a/crates/core/src/alias.rs b/crates/core/src/alias.rs index e254a8fa..beb80f27 100644 --- a/crates/core/src/alias.rs +++ b/crates/core/src/alias.rs @@ -60,10 +60,23 @@ impl RequestHeader { return Err(Error::Config(format!("Invalid value for header '{name}'"))); } - Ok(Self { + let header = Self { name, value: header_value, - }) + }; + header.validate_transport_name()?; + Ok(header) + } + + /// Transport control headers must come from the owner of the registered memory. + pub fn validate_transport_name(&self) -> Result<()> { + let name = self.name.to_ascii_lowercase(); + if name.starts_with("x-amz-rdma-") || name.starts_with("x-rustfs-nixl-") { + return Err(Error::Config( + "RDMA headers are reserved for the selected transport".into(), + )); + } + Ok(()) } } diff --git a/crates/s3/src/client.rs b/crates/s3/src/client.rs index bb837118..1039d210 100644 --- a/crates/s3/src/client.rs +++ b/crates/s3/src/client.rs @@ -1806,6 +1806,10 @@ impl Intercept for CustomHeaderInterceptor { impl S3Client { /// Create a new S3 client from an alias configuration pub async fn new(alias: Alias) -> Result { + let request_headers = global_request_headers(); + for header in &request_headers { + header.validate_transport_name()?; + } let endpoint = alias.endpoint.clone(); let region = alias.region.clone(); let access_key = alias.access_key.clone(); @@ -1865,7 +1869,6 @@ impl S3Client { let config = config_loader.load().await; // Build S3 client with path-style addressing for compatibility - let request_headers = global_request_headers(); let mut s3_config_builder = aws_sdk_s3::config::Builder::from(&config) .force_path_style(force_path_style_for_alias(&alias)) // Improve compatibility with S3-compatible backends by only sending request @@ -7698,10 +7701,8 @@ impl ObjectStore for S3Client { } } -/// External control exchanges retain the host client's TLS and signing policy. -#[async_trait] -impl ControlExecutor for S3Client { - async fn execute_headers(&self, request: ControlRequest) -> Result { +impl S3Client { + async fn send_external_control(&self, request: ControlRequest) -> Result { if self.alias.anonymous { return Err(Error::RequestRejected( "External object control requires an authenticated S3 principal".to_string(), @@ -7763,8 +7764,7 @@ impl ControlExecutor for S3Client { // Only response headers travel over HTTPS. Bound the complete wait, // including connection setup, using the same alias policy as S3. let timeout = self.alias.timeout_config(); - let mut response = self - .xml_http_client + self.xml_http_client .request(request.method, url) .headers(signed) .timeout(Duration::from_millis( @@ -7779,7 +7779,38 @@ impl ControlExecutor for S3Client { "External control exchange failed" }; Error::Network(message.to_owned()) - })?; + }) + } +} + +/// External control exchanges retain the host client's TLS and signing policy. +#[async_trait] +impl ControlExecutor for S3Client { + async fn execute_registered( + &self, + request: ControlRequest, + ) -> Result { + let method = request.method.clone(); + let conditional = request.headers.contains_key("if-match"); + let mut response = self.send_external_control(request).await?; + let status = response.status(); + let headers = std::mem::take(response.headers_mut()); + if object_error::dma_precondition_response(&method, conditional, status, &headers) + && object_error::has_precondition_error_body(response).await + { + return Ok( + data_transport::RegisteredControlResponse::RejectedBeforeDma(Error::Conflict( + "The S3 endpoint rejected the conditional GET before transferring data".into(), + )), + ); + } + Ok(data_transport::RegisteredControlResponse::Response( + ControlResponse { status, headers }, + )) + } + + async fn execute_headers(&self, request: ControlRequest) -> Result { + let mut response = self.send_external_control(request).await?; Ok(ControlResponse { status: response.status(), headers: std::mem::take(response.headers_mut()), diff --git a/crates/s3/src/client/object_error.rs b/crates/s3/src/client/object_error.rs index c17cd1f6..9b2a3a96 100644 --- a/crates/s3/src/client/object_error.rs +++ b/crates/s3/src/client/object_error.rs @@ -137,3 +137,113 @@ impl S3Client { Error::Network(formatted) } } + +/// Only a conditional GET can establish that this particular precondition +/// stopped the read before the server wrote to the advertised memory. +pub(super) fn dma_precondition_response( + method: &http::Method, + conditional: bool, + status: http::StatusCode, + headers: &http::HeaderMap, +) -> bool { + let mut codes = headers.get_all("x-amz-error-code").iter(); + method == http::Method::GET + && conditional + && status == http::StatusCode::PRECONDITION_FAILED + && !headers.keys().any(|name| { + name.as_str().starts_with("x-amz-rdma-") || name.as_str().starts_with("x-rustfs-nixl-") + }) + && codes + .next() + .is_none_or(|value| value == "PreconditionFailed") + && codes.next().is_none() +} + +fn is_s3_precondition_error(body: &[u8]) -> bool { + #[derive(serde::Deserialize)] + enum Document { + Error { + #[serde(rename = "Code")] + code: String, + }, + } + let mut xml = quick_xml::de::Deserializer::from_reader(body.trim_ascii_end()); + matches!(serde::Deserialize::deserialize(&mut xml), Ok(Document::Error {code}) if code == "PreconditionFailed") + && xml.is_empty() +} + +pub(super) async fn has_precondition_error_body(mut response: reqwest::Response) -> bool { + const LIMIT: usize = 16 * 1024; + let mut body = Vec::new(); + loop { + match response.chunk().await { + Ok(Some(chunk)) if chunk.len() <= LIMIT - body.len() => body.extend_from_slice(&chunk), + Ok(None) => return is_s3_precondition_error(&body), + _ => return false, + } + } +} + +#[cfg(test)] +mod dma_tests { + use super::*; + use http::{HeaderMap, Method, StatusCode}; + #[test] + fn requires_a_conditional_get_and_unambiguous_s3_rejection() { + let status = StatusCode::PRECONDITION_FAILED; + let headers = HeaderMap::new(); + let s3 = b"PreconditionFailedetag"; + assert!(dma_precondition_response( + &Method::GET, + true, + status, + &headers + )); + assert!(!dma_precondition_response( + &Method::PUT, + true, + status, + &headers + )); + assert!(!dma_precondition_response( + &Method::GET, + false, + status, + &headers + )); + assert!(!dma_precondition_response( + &Method::GET, + true, + StatusCode::BAD_GATEWAY, + &headers + )); + for name in [ + "x-amz-rdma-reply", + "x-amz-rdma-bytes-transferred", + "x-amz-rdma-extra", + ] { + let mut headers = HeaderMap::new(); + headers.insert(name, "0".parse().unwrap()); + assert!(!dma_precondition_response( + &Method::GET, + true, + status, + &headers + )); + } + assert!(is_s3_precondition_error(s3)); + assert!(is_s3_precondition_error( + b"\nPreconditionFailed\n" + )); + for body in [ + &b""[..], + b"PreconditionFailed", + b"PreconditionFailed", + b"PreconditionFailed", + b"Other", + b"PreconditionFailedOther", + ] { + assert!(!is_s3_precondition_error(body)); + } + } +} diff --git a/crates/s3/src/data_transport.rs b/crates/s3/src/data_transport.rs index 81350e56..6f4374fe 100644 --- a/crates/s3/src/data_transport.rs +++ b/crates/s3/src/data_transport.rs @@ -33,12 +33,29 @@ pub struct ControlResponse { pub headers: HeaderMap, } +/// Outcome of an exchange that advertised client memory. +pub enum RegisteredControlResponse { + Response(ControlResponse), + /// The authenticated peer rejected the request before starting any data transfer. + RejectedBeforeDma(Error), +} + /// Host-owned HTTPS, credentials, signing, custom headers, and TLS configuration. #[async_trait] pub trait ControlExecutor: Send + Sync { /// Read only the status and headers. A declined external GET can return an /// ordinary S3 payload of arbitrary size. async fn execute_headers(&self, request: ControlRequest) -> Result; + + /// Executors that cannot establish a pre-transfer rejection return ordinary responses. + async fn execute_registered( + &self, + request: ControlRequest, + ) -> Result { + self.execute_headers(request) + .await + .map(RegisteredControlResponse::Response) + } } /// External transport construction is separate from process-wide policy. diff --git a/docs/rdma-build.md b/docs/rdma-build.md index e347a351..b8e0ecd2 100644 --- a/docs/rdma-build.md +++ b/docs/rdma-build.md @@ -49,7 +49,8 @@ rc --data-transport rdma --rdma-backend nixl get other/models/model.bin from-nix Configure `lab` as a verified HTTPS alias for a RustFS server built with `--features cuobject` and `RUSTFS_CUOBJECT_ENABLE=true`. Use an alias for a NIXL-enabled server with the `nixl` backend. `RC_RDMA_BACKEND` sets the -backend for subsequent commands. The `rdma` policy requires the selected +backend for subsequent commands. Request headers in the `x-amz-rdma-*` and +`x-rustfs-nixl-*` namespaces are reserved for the selected provider. The `rdma` policy requires the selected backend. The `auto` policy allows a safe S3 fallback when that backend is unavailable. The default `http` policy transfers the payload through S3. @@ -64,7 +65,12 @@ destination file. A range GET for the next window can proceed while the previous window is being written. All requests keep the caller's version selector. Each GET uses `If-Match` and checks the version from HEAD before delivering that range. Downloads publish the temporary file after verifying the transfer count and any applicable object checksum. -A window with an uncertain transfer stays registered until the process exits. +A verified receipt releases the window. A local rejection before sending or +an authenticated S3 `PreconditionFailed` response to an `If-Match` GET also +releases it. For the latter, the client requires HTTP 412, a bounded S3 +error document and no RDMA response headers. An ambiguous response, a +missing receipt, cancellation or timeout retains the token and window until +the process exits. When both windows are unavailable for this reason, waiting operations use a fresh pool within the process registration budget. diff --git a/nixl/src/nvidia.rs b/nixl/src/nvidia.rs index 9dc08dae..5db47bd8 100644 --- a/nixl/src/nvidia.rs +++ b/nixl/src/nvidia.rs @@ -23,7 +23,37 @@ pub(super) fn register(size: usize, count: usize) -> Result> { pub(super) struct HostBuffer(ClientBuffer>); -type Token<'a> = ClientToken<'a, Arc>; +pub(crate) struct Token<'a> { + raw: ClientToken<'a, Arc>, + // Fields drop in declaration order, so the witness runs after the SDK destructor. + #[cfg(test)] + after_release: Option, +} + +#[cfg(test)] +struct ReleaseWitness(Arc); + +#[cfg(test)] +impl Drop for ReleaseWitness { + fn drop(&mut self) { + self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + } +} + +#[cfg(test)] +impl Exposure { + pub(crate) fn holds_token(&self, advertised: &HeaderValue) -> bool { + self.borrow_dependent().raw.as_str().as_bytes() == advertised.as_bytes() + } + + pub(crate) fn observe_token_release(&mut self) -> Arc { + let count = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + self.with_dependent_mut(|_, token| { + token.after_release = Some(ReleaseWitness(count.clone())) + }); + count + } +} // Dropping the token releases its SDK QP reference. Keep it with the memory // registration through cancellation, timeout, and any unconfirmed receipt. @@ -59,8 +89,12 @@ impl HostBuffer { Method::PUT => Operation::Put, _ => return Err(Error::General("Unsupported cuObject operation".into())), }; - let token = self.0.token(0, len, operation).map_err(sdk_error)?; - let mut value = HeaderValue::from_str(token.as_str()) + let token = Token { + raw: self.0.token(0, len, operation).map_err(sdk_error)?, + #[cfg(test)] + after_release: None, + }; + let mut value = HeaderValue::from_str(token.raw.as_str()) .map_err(|_| Error::General("Invalid NVIDIA cuObject token".into()))?; value.set_sensitive(true); headers.insert(cuobject::TOKEN_HEADER, value); diff --git a/nixl/src/pool.rs b/nixl/src/pool.rs index 60d0e177..5dd296e4 100644 --- a/nixl/src/pool.rs +++ b/nixl/src/pool.rs @@ -228,6 +228,20 @@ mod tests { check_window_lifetime(RdmaBackend::CuObject).await; } + fn observe(exposed: Exposed) -> (Exposed, Option>) { + #[cfg(feature = "cuobject")] + { + let mut exposed = exposed; + let release = match exposed.0.as_mut() { + Some(Transfer::CuObject(offer)) => Some(offer.observe_token_release()), + _ => None, + }; + (exposed, release) + } + #[cfg(not(feature = "cuobject"))] + (exposed, None) + } + async fn check_window_lifetime(backend: RdmaBackend) { let pools = Pools::new(backend); let first = pools.reserve(32).await.unwrap(); @@ -242,7 +256,8 @@ mod tests { _ = std::future::ready(()) => {} } let mut headers = HeaderMap::new(); - let first = first.expose(&Method::GET, 32, &mut headers).unwrap(); + let (first, first_releases) = + observe(first.expose(&Method::GET, 32, &mut headers).unwrap()); #[cfg(feature = "cuobject")] if backend == RdmaBackend::CuObject { assert!(headers[cuobject::TOKEN_HEADER].is_sensitive()); @@ -251,12 +266,17 @@ mod tests { std::future::pending::<()>().await; exposed.finished() }; - let cancelled = tokio::spawn(exchanging(first)); + let (started, ready) = tokio::sync::oneshot::channel(); + let cancelled = tokio::spawn(async move { + started.send(()).unwrap(); + exchanging(first).await + }); + ready.await.unwrap(); cancelled.abort(); assert!(matches!(cancelled.await, Err(e) if e.is_cancelled())); - let second = second - .expose(&Method::PUT, 32, &mut HeaderMap::new()) - .unwrap(); + let mut put_headers = HeaderMap::new(); + let second = second.expose(&Method::PUT, 32, &mut put_headers).unwrap(); + let (second, second_releases) = observe(second); assert!( tokio::time::timeout(Duration::from_millis(1), exchanging(second)) .await @@ -267,14 +287,44 @@ mod tests { result = waiting => assert!(result.unwrap().is_none()), _ = std::future::ready(()) => panic!("retiring a pool must wake its waiters immediately"), } + #[cfg(feature = "cuobject")] + if backend == RdmaBackend::CuObject { + let retained = QUARANTINE.lock().unwrap(); + for advertised in [ + &headers[cuobject::TOKEN_HEADER], + &put_headers[cuobject::TOKEN_HEADER], + ] { + assert!(retained.iter().any(|transfer| matches!(transfer, Transfer::CuObject(offer) + if Arc::ptr_eq(&offer.borrow_owner().pool, &old) && offer.holds_token(advertised)))); + } + } let replacement = pools.reserve(32).await.unwrap(); assert!(!Arc::ptr_eq(&old, &replacement.pool)); let fresh_pool = replacement.pool.clone(); - let returned = replacement - .expose(&Method::GET, 32, &mut HeaderMap::new()) - .unwrap() - .finished(); + let (completed, completed_releases) = observe( + replacement + .expose(&Method::GET, 32, &mut HeaderMap::new()) + .unwrap(), + ); + let returned = completed.finished(); + if let Some(count) = &completed_releases { + assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 1); + } drop(returned); + if backend == RdmaBackend::CuObject { + for counter in [first_releases, second_releases] { + assert_eq!( + counter.unwrap().load(std::sync::atomic::Ordering::SeqCst), + 0 + ); + } + assert_eq!( + completed_releases + .unwrap() + .load(std::sync::atomic::Ordering::SeqCst), + 1 + ); + } assert_eq!(fresh_pool.available.available_permits(), WINDOWS_PER_POOL); assert_eq!(old.available.available_permits(), 0); } diff --git a/nixl/src/transport.rs b/nixl/src/transport.rs index 952e0a39..27b26a93 100644 --- a/nixl/src/transport.rs +++ b/nixl/src/transport.rs @@ -55,8 +55,12 @@ impl Transport { request: ControlRequest, exposed: Exposed, ) -> DataTransportResult<(ControlResponse, Exposed)> { - match self.control.execute_headers(request).await { - Ok(response) => Ok((response, exposed)), + match self.control.execute_registered(request).await { + Ok(RegisteredControlResponse::Response(response)) => Ok((response, exposed)), + Ok(RegisteredControlResponse::RejectedBeforeDma(error)) => { + drop(exposed.finished()); + Err(rejected(error)) + } Err(error @ Error::RequestRejected(_)) => { // ControlExecutor rejected the request locally before sending it. drop(exposed.finished()); diff --git a/nixl/src/transport/download.rs b/nixl/src/transport/download.rs index e1b38423..790dab86 100644 --- a/nixl/src/transport/download.rs +++ b/nixl/src/transport/download.rs @@ -70,7 +70,7 @@ impl Transport { if !response.headers.contains_key(RDMA_REPLY_HEADER) { // An ordinary successful GET returned the object in its HTTP body. // It is safe to try the ordinary reader before publishing any bytes. - drop(exposed.finished()); + // A missing receipt permits the S3 fallback but does not prove the window is idle. return Err(unavailable(Error::UnsupportedFeature( "The endpoint served GET over HTTP".into(), ))); diff --git a/nixl/src/transport/tests.rs b/nixl/src/transport/tests.rs index 6ef57cdc..34bfee0f 100644 --- a/nixl/src/transport/tests.rs +++ b/nixl/src/transport/tests.rs @@ -125,3 +125,108 @@ async fn a_delete_marker_keeps_its_version_and_exit_code() { ); } } + +#[tokio::test] +async fn only_proven_conditional_rejections_reuse_the_registered_window() { + struct Peer(Mutex>); + #[async_trait] + impl ControlExecutor for Peer { + async fn execute_headers(&self, req: ControlRequest) -> Result { + assert_eq!(req.method, Method::HEAD); + let mut headers = HeaderMap::new(); + headers.insert("etag", HeaderValue::from_static("\"etag\"")); + headers.insert("content-length", HeaderValue::from_static("0")); + Ok(ControlResponse { + status: StatusCode::OK, + headers, + }) + } + async fn execute_registered( + &self, + req: ControlRequest, + ) -> Result { + assert_eq!(req.method, Method::GET); + assert!(req.headers.contains_key("if-match")); + let mut seen = self.0.lock().unwrap(); + seen.push(req.headers[rustfs_nixl::NIXL_BUFFER_HEADER].clone()); + Ok(match seen.len() { + 1 => RegisteredControlResponse::Response(ControlResponse { + status: StatusCode::PRECONDITION_FAILED, + headers: HeaderMap::new(), + }), + 2..=19 => RegisteredControlResponse::RejectedBeforeDma(Error::Conflict( + "PreconditionFailed".into(), + )), + _ => { + let mut headers = HeaderMap::new(); + headers.insert(RDMA_REPLY_HEADER, HeaderValue::from_static("200")); + RegisteredControlResponse::Response(ControlResponse { + status: StatusCode::OK, + headers, + }) + } + }) + } + } + let peer = Arc::new(Peer(Mutex::default())); + let transport = Factory(RdmaBackend::Nixl).create(peer.clone()).unwrap(); + let path = RemotePath::new("test", "bucket", "key"); + let opts = rc_core::TransferReadOptions::default(); + for i in 1..=20 { + let r = transport + .download( + DownloadRequest { + path: &path, + options: &opts, + max_bytes: None, + max_receive_bytes: 64, + on_progress: &mut |_, _| {}, + }, + &mut tokio::io::sink(), + ) + .await; + assert_eq!(r.is_ok(), i == 20); + } + let seen = peer.0.lock().unwrap(); + assert_ne!(seen[0], seen[1]); + assert!(seen[1..].iter().all(|v| v == seen[1])); +} + +#[cfg(feature = "cuobject")] +#[tokio::test] +#[ignore = "requires an NVIDIA RDMA device and an authenticated RustFS object"] +async fn rustfs_declines_a_stale_conditional_get_before_dma() { + let env = |key| { + std::env::var(key) + .expect("configure the test endpoint, credentials, CA and existing bucket") + }; + let mut alias = rc_core::Alias::new( + "test", + env("RC_TEST_ENDPOINT"), + env("AWS_ACCESS_KEY_ID"), + env("AWS_SECRET_ACCESS_KEY"), + ); + alias.ca_bundle = Some(env("RC_TEST_CA")); + let client = rc_s3::S3Client::new(alias).await.unwrap(); + let path = RemotePath::new("test", env("RC_TEST_BUCKET"), "known"); + let transport = Transport { + control: Arc::new(client), + pools: Pools::new(RdmaBackend::CuObject), + }; + for _ in 0..20 { + let mut headers = HeaderMap::new(); + headers.insert("if-match", HeaderValue::from_static("\"stale\"")); + let exposed = transport + .pools + .reserve(4096) + .await + .unwrap() + .expose(&Method::GET, 4096, &mut headers) + .unwrap(); + let req = wire::request(Method::GET, &path, vec![], headers); + match transport.exchange(req, exposed).await { + Err(error) if matches!(error.source.as_deref(), Some(Error::Conflict(_))) => {} + _ => panic!("expected an authenticated pre-transfer rejection"), + } + } +} diff --git a/nixl/src/transport/upload.rs b/nixl/src/transport/upload.rs index ed84a6f7..7906699e 100644 --- a/nixl/src/transport/upload.rs +++ b/nixl/src/transport/upload.rs @@ -145,7 +145,7 @@ impl Transport { return Err(rejected(response.object_error(request.path, None))); } if !response.headers.contains_key(RDMA_REPLY_HEADER) { - drop(exposed.finished()); + // A missing receipt permits the S3 fallback but does not prove the window is idle. return Ok(None); } wire::receipt(StatusCode::OK, &response.headers, len as u64).map_err(unknown)?; From b2a8a569b78447758641dc3cfa4939ffa21d534b Mon Sep 17 00:00:00 2001 From: gatewayj <835269233@qq.com> Date: Sat, 21 Nov 2026 23:30:10 +0800 Subject: [PATCH 03/13] docs: define the cuObject registered memory safety exception --- AGENTS.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index ebb78d75..68c30379 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -103,9 +103,10 @@ Modifying protected files requires: - Must use `?` or `expect("reason")` - Violation: may cause panic -3. **Using `unsafe` code** - - No exceptions - - Violation: security risk +3. **Using `unsafe` code outside the cuObject host-buffer accessor** + - With the `cuobject` feature enabled, only `HostBuffer::writable` in `nixl/src/nvidia.rs` may use `unsafe`, solely to call `ClientBuffer::slice_mut` over its owned registration. + - The returned slice must borrow the window exclusively. Once the token is exposed, retain it with the registration until a verified completion or proof that DMA never started. If the outcome is unknown, keep both quarantined for the life of the process. + - Keep the safety comment and lint exception on this accessor. Native builds without `cuobject` must retain `forbid(unsafe_code)`. 4. **Printing credentials in logs/errors** - Includes: access_key, secret_key, Authorization headers From a03f2a736a99759fc69c2ce9752c3647c3de81ba Mon Sep 17 00:00:00 2001 From: gatewayj <835269233@qq.com> Date: Sat, 21 Nov 2026 23:47:17 +0800 Subject: [PATCH 04/13] refactor(transfer): bind the NVIDIA cuObject client SDK directly --- AGENTS.md | 8 +- docs/ADR/0001-object-data-transport.md | 6 +- docs/rdma-build.md | 1 + nixl/Cargo.lock | 147 +++++++++++++++++-------- nixl/Cargo.toml | 8 +- nixl/build.rs | 43 ++++++++ nixl/native/cuobject.cc | 130 ++++++++++++++++++++++ nixl/native/cuobject.h | 29 +++++ nixl/src/nvidia.rs | 122 +++++++++----------- nixl/src/nvidia/sdk.rs | 26 +++++ nixl/src/pool.rs | 91 +++++++-------- nixl/src/transport.rs | 4 +- nixl/src/transport/download.rs | 2 +- nixl/src/transport/upload.rs | 2 +- nixl/src/wire/native_test.rs | 2 +- 15 files changed, 436 insertions(+), 185 deletions(-) create mode 100644 nixl/build.rs create mode 100644 nixl/native/cuobject.cc create mode 100644 nixl/native/cuobject.h create mode 100644 nixl/src/nvidia/sdk.rs diff --git a/AGENTS.md b/AGENTS.md index 68c30379..0b5296b4 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -103,10 +103,10 @@ Modifying protected files requires: - Must use `?` or `expect("reason")` - Violation: may cause panic -3. **Using `unsafe` code outside the cuObject host-buffer accessor** - - With the `cuobject` feature enabled, only `HostBuffer::writable` in `nixl/src/nvidia.rs` may use `unsafe`, solely to call `ClientBuffer::slice_mut` over its owned registration. - - The returned slice must borrow the window exclusively. Once the token is exposed, retain it with the registration until a verified completion or proof that DMA never started. If the outcome is unknown, keep both quarantined for the life of the process. - - Keep the safety comment and lint exception on this accessor. Native builds without `cuobject` must retain `forbid(unsafe_code)`. +3. **Using `unsafe` outside the private NVIDIA SDK bridge** + - Only the private bridge in `nixl/src/nvidia/sdk.rs`, behind the `cuobject` feature, may declare the C++ interface and the thread ownership of its opaque window. Keep handwritten Rust operations outside this exception. + - Native host slices require an exclusive window. Once a token is exposed, retain it with its registration until confirmed completion or proof that DMA never started. Quarantine an uncertain exchange or failed token release for the life of the process. + - Keep the lint exception on the bridge. Native builds without `cuobject` must retain `forbid(unsafe_code)`. 4. **Printing credentials in logs/errors** - Includes: access_key, secret_key, Authorization headers diff --git a/docs/ADR/0001-object-data-transport.md b/docs/ADR/0001-object-data-transport.md index 8f7d3e6b..dbceea1f 100644 --- a/docs/ADR/0001-object-data-transport.md +++ b/docs/ADR/0001-object-data-transport.md @@ -17,9 +17,9 @@ The common launcher preserves command dispatch, output, exit codes, and the existing worker-thread configuration. The NIXL backend supplies agent metadata and a registered buffer description. -The NVIDIA cuObject backend supplies a direction-specific SDK token for the -registered host buffer. Each token stays alive with its buffer until a -receipt confirms completion. An uncertain transfer retains both resources +The NVIDIA cuObject backend uses a private CXX bridge to register host memory with +`cuObjClient` and acquire a direction-specific token for each transfer. The window can be reused after +a verified receipt or proof that DMA never started. An uncertain transfer retains both resources within the process registration budget. Both use the host-owned `ControlExecutor`. The S3 client signs and sends a bodyless HTTPS request on the shared S3 HTTP client using the alias timeout policy. It returns the status and headers directly, including duplicate headers. The provider verifies the RustFS transfer receipt diff --git a/docs/rdma-build.md b/docs/rdma-build.md index b8e0ecd2..f2b3666e 100644 --- a/docs/rdma-build.md +++ b/docs/rdma-build.md @@ -34,6 +34,7 @@ to the same executable, install the NVIDIA cuObject **client** SDK, cuFile development libraries, libibverbs development headers and CUDA headers for the target architecture. Set `CUOBJCLIENT_ROOT` to the SDK prefix and `CUDA_HOME` to the CUDA toolkit. +The CLI builds its C++17 adapter against `cuobjclient.h` and links directly to the NVIDIA SDK. The SDK's `libcuobjclient`, `libcufile` and RDMA plugin must be available at runtime. Set `CUOBJ_ENV_PATH_JSON` to the NVIDIA client configuration that selects the application RDMA device. diff --git a/nixl/Cargo.lock b/nixl/Cargo.lock index 7eacb986..b4ac96e1 100644 --- a/nixl/Cargo.lock +++ b/nixl/Cargo.lock @@ -681,7 +681,7 @@ dependencies = [ "clang-sys", "itertools", "log", - "prettyplease 0.2.37", + "prettyplease", "proc-macro2", "quote", "regex", @@ -690,24 +690,6 @@ dependencies = [ "syn 2.0.119", ] -[[package]] -name = "bindgen" -version = "0.73.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "787ef8ef523575546b106a58213d6e6b06198a05c2f757258c68a74273670cfa" -dependencies = [ - "bitflags", - "cexpr", - "clang-sys", - "prettyplease 0.3.0", - "proc-macro2", - "quote", - "regex", - "rustc-hash", - "shlex 2.0.1", - "syn 3.0.10", -] - [[package]] name = "bitflags" version = "2.13.2" @@ -892,6 +874,17 @@ version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" +[[package]] +name = "codespan-reporting" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681" +dependencies = [ + "serde", + "termcolor", + "unicode-width", +] + [[package]] name = "colorchoice" version = "1.0.5" @@ -1057,24 +1050,65 @@ dependencies = [ ] [[package]] -name = "cuobject" -version = "0.1.0" +name = "cxx" +version = "1.0.205" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "486fec9045f8057131bf4bba71fbb87bf9dd3e44f853622cf7fa42713f3a108c" +checksum = "c8a02bfeba9074b2bbb39492c9b0908ec854f455a3cccdcde7a1de55e2315e40" dependencies = [ - "cuobject-sys", - "memmap2", - "thiserror", + "cc", + "cxx-build", + "cxxbridge-cmd", + "cxxbridge-flags", + "cxxbridge-macro", + "foldhash", + "link-cplusplus", ] [[package]] -name = "cuobject-sys" -version = "0.1.0" +name = "cxx-build" +version = "1.0.205" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edc615b2a037eb0d80180d202f809629155742db9c9e94b9f7696b1100a7d52f" +checksum = "bbc2ac76997619d2d888b58ad79488f1c835de41ca4dd3dd7082acf4ecb0a50f" dependencies = [ - "bindgen 0.73.2", "cc", + "codespan-reporting", + "indexmap", + "proc-macro2", + "quote", + "scratch", + "syn 3.0.10", +] + +[[package]] +name = "cxxbridge-cmd" +version = "1.0.205" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54a486ed16a3f2a053fe7f5b98db4c1a59846a23e8cb9e49f9d1bd48830d51a2" +dependencies = [ + "clap", + "codespan-reporting", + "indexmap", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "cxxbridge-flags" +version = "1.0.205" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c72569be94e2283764d334cd285980b747dbe221e27e315484eb6bcd93fa808a" + +[[package]] +name = "cxxbridge-macro" +version = "1.0.205" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "423e795284a7f7b3f843c956a5322c4bc497b60c2dd1a6339da10313cb18d575" +dependencies = [ + "indexmap", + "proc-macro2", + "quote", + "syn 3.0.10", ] [[package]] @@ -1920,6 +1954,15 @@ dependencies = [ "libc", ] +[[package]] +name = "link-cplusplus" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f78c730aaa7d0b9336a299029ea49f9ee53b0ed06e9202e8cb7db9bae7b8c82" +dependencies = [ + "cc", +] + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -2072,7 +2115,7 @@ version = "1.6.0" source = "git+https://github.com/houseme/nixl?rev=cc636c83f13d692e85b67e55aed092413d16fb41#cc636c83f13d692e85b67e55aed092413d16fb41" dependencies = [ "anyhow", - "bindgen 0.71.1", + "bindgen", "cc", "libc", "os_info", @@ -2543,16 +2586,6 @@ dependencies = [ "syn 2.0.119", ] -[[package]] -name = "prettyplease" -version = "0.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2bfe0f4c752e450fc2faf62654f1c134747922825d5b04ca717b8874f41a40c0" -dependencies = [ - "proc-macro2", - "syn 3.0.10", -] - [[package]] name = "proc-macro2" version = "1.0.107" @@ -2965,14 +2998,14 @@ version = "0.1.0" dependencies = [ "async-trait", "base64 0.22.1", - "cuobject", + "cxx", + "cxx-build", "getrandom 0.4.3", "http", "rc-core", "rc-s3", "rustfs-cli", "rustfs-nixl", - "self_cell", "tokio", ] @@ -3089,6 +3122,12 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "scratch" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d68f2ec51b097e4c1a75b681a8bec621909b5e91f15bb7b840c4f2f7b01148b2" + [[package]] name = "security-framework" version = "3.7.0" @@ -3112,12 +3151,6 @@ dependencies = [ "libc", ] -[[package]] -name = "self_cell" -version = "1.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813" - [[package]] name = "semver" version = "1.0.28" @@ -3418,6 +3451,15 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + [[package]] name = "thiserror" version = "2.0.21" @@ -3949,6 +3991,15 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" diff --git a/nixl/Cargo.toml b/nixl/Cargo.toml index 1e5b4792..e79a208d 100644 --- a/nixl/Cargo.toml +++ b/nixl/Cargo.toml @@ -14,11 +14,10 @@ name = "rc" path = "src/main.rs" [features] -cuobject = ["dep:cuobject", "dep:self_cell"] +cuobject = ["dep:cxx", "dep:cxx-build"] [dependencies] -cuobject = { version = "0.1.0", default-features = false, features = ["client"], optional = true } -self_cell = { version = "1.2", optional = true } +cxx = { version = "1", optional = true } rustfs-cli = { path = "../crates/cli" } rc-core = { path = "../crates/core" } rc-s3 = { path = "../crates/s3" } @@ -28,3 +27,6 @@ base64 = "0.22" getrandom = "0.4" http = "1" tokio = { version = "1", features = ["io-util", "sync", "time"] } + +[build-dependencies] +cxx-build = { version = "1", optional = true } diff --git a/nixl/build.rs b/nixl/build.rs new file mode 100644 index 00000000..8fbad863 --- /dev/null +++ b/nixl/build.rs @@ -0,0 +1,43 @@ +fn main() { + #[cfg(feature = "cuobject")] + build_cuobject(); +} + +#[cfg(feature = "cuobject")] +fn build_cuobject() { + use std::{env, path::PathBuf}; + + for name in ["CUOBJCLIENT_ROOT", "CUDA_HOME"] { + println!("cargo:rerun-if-env-changed={name}"); + } + for file in [ + "src/nvidia/sdk.rs", + "native/cuobject.h", + "native/cuobject.cc", + ] { + println!("cargo:rerun-if-changed={file}"); + } + let cuda = env::var_os("CUDA_HOME") + .map(PathBuf::from) + .unwrap_or_else(|| PathBuf::from("/usr/local/cuda")); + let sdk = env::var_os("CUOBJCLIENT_ROOT") + .map(PathBuf::from) + .unwrap_or_else(|| cuda.clone()); + cxx_build::bridge("src/nvidia/sdk.rs") + .file("native/cuobject.cc") + .include(".") + .include(sdk.join("include")) + .include(cuda.join("include")) + .std("c++17") + .compile("rc_cuobject"); + for prefix in [&sdk, &cuda] { + for dir in ["lib", "lib64"] { + println!( + "cargo:rustc-link-search=native={}", + prefix.join(dir).display() + ); + } + } + println!("cargo:rustc-link-lib=cuobjclient"); + println!("cargo:rustc-link-lib=cufile"); +} diff --git a/nixl/native/cuobject.cc b/nixl/native/cuobject.cc new file mode 100644 index 00000000..bddb11a2 --- /dev/null +++ b/nixl/native/cuobject.cc @@ -0,0 +1,130 @@ +#include "native/cuobject.h" +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace rc::cuobject { + +class Client final { +public: + // Only the descriptor API is used. The signed S3 control exchange runs in Rust. + CUObjOps_t ops{}; + cuObjClient sdk{ops, CUOBJ_PROTO_RDMA_DC_V1}; + std::mutex mutex; +}; + +std::shared_ptr make_client() { return std::make_shared(); } + +static void check(cuObjErr_t status, const char *operation) { + if (status != CU_OBJ_SUCCESS) { + throw std::runtime_error(std::string(operation) + " failed with cuObject status " + + std::to_string(static_cast(status))); + } +} + +struct NativeWindow::Registration { + std::shared_ptr client; + std::size_t size; + std::uint8_t *data; + char *token = nullptr; + bool release_failed = false; + + Registration(std::shared_ptr owner, std::size_t length) + : client(std::move(owner)), size(length) { + if (!client) { + throw std::invalid_argument("missing cuObject client"); + } + if (length == 0) { + throw std::invalid_argument("invalid cuObject registration length"); + } + void *mapping = mmap(nullptr, length, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (mapping == MAP_FAILED) { + throw std::system_error(errno, std::generic_category(), "mmap"); + } + data = static_cast(mapping); + try { + std::lock_guard lock(client->mutex); + check(client->sdk.cuMemObjGetDescriptor(data, size), "register memory"); + } catch (...) { + munmap(data, size); + throw; + } + } + + ~Registration() { munmap(data, size); } +}; + +NativeWindow::NativeWindow(std::shared_ptr client, std::size_t size) + : registration_(std::make_unique(std::move(client), size)) {} + +NativeWindow::~NativeWindow() { + auto &r = *registration_; + // An active token or a failed deregistration must keep the client and mapping alive. + if (!r.token && !r.release_failed) { + try { + std::lock_guard lock(r.client->mutex); + if (r.client->sdk.cuMemObjPutDescriptor(r.data) == CU_OBJ_SUCCESS) { + return; + } + } catch (...) { + // The SDK did not confirm deregistration. + } + } + registration_.release(); +} + +std::unique_ptr register_window(std::shared_ptr client, std::size_t size) { + return std::make_unique(std::move(client), size); +} + +rust::Slice NativeWindow::writable() { + auto &r = *registration_; + if (r.token || r.release_failed) { + throw std::logic_error("cuObject window still exposed"); + } + return {r.data, r.size}; +} + +void NativeWindow::acquire(std::size_t length, bool for_get) { + auto &r = *registration_; + if (r.token || r.release_failed || length == 0 || length > r.size) { + throw std::invalid_argument("invalid cuObject token request"); + } + std::lock_guard lock(r.client->mutex); + check(r.client->sdk.cuMemObjGetRDMAToken(r.data, length, 0, for_get ? CUOBJ_GET : CUOBJ_PUT, + &r.token), "acquire token"); + if (!r.token || !*r.token) { + throw std::runtime_error("cuObject returned an empty token"); + } +} + +rust::Slice NativeWindow::active_token() const noexcept { + const char *token = registration_->token; + if (!token) { + return {}; + } + return {reinterpret_cast(token), std::strlen(token)}; +} + +void NativeWindow::release_token() { + auto &r = *registration_; + if (r.release_failed) { + throw std::runtime_error("previous cuObject token release failed"); + } + if (r.token) { + std::lock_guard lock(r.client->mutex); + // The SDK may consume the string even when it reports a failure. + r.release_failed = true; + check(r.client->sdk.cuMemObjPutRDMAToken(std::exchange(r.token, nullptr)), "release token"); + r.release_failed = false; + } +} + +} // namespace rc::cuobject diff --git a/nixl/native/cuobject.h b/nixl/native/cuobject.h new file mode 100644 index 00000000..f89347ff --- /dev/null +++ b/nixl/native/cuobject.h @@ -0,0 +1,29 @@ +#pragma once + +#include "rust/cxx.h" +#include +#include +#include + +namespace rc::cuobject { + +class Client; +std::shared_ptr make_client(); + +class NativeWindow final { +public: + NativeWindow(std::shared_ptr client, std::size_t size); + ~NativeWindow(); + rust::Slice writable(); + void acquire(std::size_t length, bool for_get); + rust::Slice active_token() const noexcept; + void release_token(); + +private: + struct Registration; + std::unique_ptr registration_; +}; + +std::unique_ptr register_window(std::shared_ptr client, std::size_t size); + +} // namespace rc::cuobject diff --git a/nixl/src/nvidia.rs b/nixl/src/nvidia.rs index 5db47bd8..9121b0a2 100644 --- a/nixl/src/nvidia.rs +++ b/nixl/src/nvidia.rs @@ -1,103 +1,83 @@ -//! NVIDIA DC token ownership and registered host memory. +//! Direct NVIDIA client registrations for the shared S3 transfer pipeline. use crate::buffer::Buffer; -use crate::pool::Window; -use cuobject::{Client, ClientBuffer, ClientToken, Operation}; use http::{HeaderMap, HeaderValue, Method}; use rc_core::{Error, Result}; -use std::sync::Arc; -fn sdk_error(error: cuobject::Error) -> Error { +pub(super) const TOKEN_HEADER: &str = "x-amz-rdma-token"; + +#[expect( + unsafe_code, + reason = "private SDK declarations and native window thread ownership" +)] +mod sdk; +use sdk::ffi; + +fn sdk_error(error: cxx::Exception) -> Error { Error::General(format!("NVIDIA cuObject: {error}")) } pub(super) fn register(size: usize, count: usize) -> Result> { - let client = Arc::new(Client::new().map_err(sdk_error)?); + let client = ffi::make_client().map_err(sdk_error)?; (0..count) .map(|_| { - let buffer = ClientBuffer::new(client.clone(), size).map_err(sdk_error)?; - Ok(Buffer::CuObject(HostBuffer(buffer))) + let raw = ffi::register_window(client.clone(), size).map_err(sdk_error)?; + Ok(Buffer::CuObject(HostBuffer { + raw, + #[cfg(test)] + releases: Default::default(), + })) }) .collect() } -pub(super) struct HostBuffer(ClientBuffer>); - -pub(crate) struct Token<'a> { - raw: ClientToken<'a, Arc>, - // Fields drop in declaration order, so the witness runs after the SDK destructor. +pub(super) struct HostBuffer { + raw: cxx::UniquePtr, #[cfg(test)] - after_release: Option, -} - -#[cfg(test)] -struct ReleaseWitness(Arc); - -#[cfg(test)] -impl Drop for ReleaseWitness { - fn drop(&mut self) { - self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst); - } -} - -#[cfg(test)] -impl Exposure { - pub(crate) fn holds_token(&self, advertised: &HeaderValue) -> bool { - self.borrow_dependent().raw.as_str().as_bytes() == advertised.as_bytes() - } - - pub(crate) fn observe_token_release(&mut self) -> Arc { - let count = Arc::new(std::sync::atomic::AtomicUsize::new(0)); - self.with_dependent_mut(|_, token| { - token.after_release = Some(ReleaseWitness(count.clone())) - }); - count - } + pub(super) releases: std::sync::Arc, } -// Dropping the token releases its SDK QP reference. Keep it with the memory -// registration through cancellation, timeout, and any unconfirmed receipt. -self_cell::self_cell!( - pub(crate) struct Exposure { - owner: Window, - #[covariant] - dependent: Token, - } -); - impl HostBuffer { - #[expect( - unsafe_code, - reason = "the SDK exposes registered host memory through raw slices" - )] pub(super) fn writable(&mut self) -> Result<&mut [u8]> { - // SAFETY: ClientBuffer::new owns this entire host mapping. A Window - // gives the caller exclusive access. Exposing it moves the Window - // and keeps the token alive until the peer confirms completion or - // declines the transfer. An uncertain transfer is never reissued. - unsafe { self.0.slice_mut(0, self.0.len()) }.map_err(sdk_error) + self.raw.pin_mut().writable().map_err(sdk_error) } pub(super) fn describe( - &self, + &mut self, method: &Method, len: usize, headers: &mut HeaderMap, - ) -> Result> { - let operation = match *method { - Method::GET => Operation::Get, - Method::PUT => Operation::Put, + ) -> Result<()> { + let for_get = match *method { + Method::GET => true, + Method::PUT => false, _ => return Err(Error::General("Unsupported cuObject operation".into())), }; - let token = Token { - raw: self.0.token(0, len, operation).map_err(sdk_error)?, - #[cfg(test)] - after_release: None, - }; - let mut value = HeaderValue::from_str(token.raw.as_str()) + self.raw + .pin_mut() + .acquire(len, for_get) + .map_err(sdk_error)?; + let mut value = HeaderValue::from_bytes(self.raw.active_token()) .map_err(|_| Error::General("Invalid NVIDIA cuObject token".into()))?; value.set_sensitive(true); - headers.insert(cuobject::TOKEN_HEADER, value); - Ok(token) + headers.insert(TOKEN_HEADER, value); + Ok(()) + } + + pub(super) fn release_token(&mut self) -> Result<()> { + #[cfg(test)] + let active = !self.raw.active_token().is_empty(); + self.raw.pin_mut().release_token().map_err(sdk_error)?; + #[cfg(test)] + if active { + self.releases + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + } + Ok(()) + } + + #[cfg(test)] + pub(super) fn holds_token(&self, advertised: &HeaderValue) -> bool { + self.raw.active_token() == advertised.as_bytes() } } diff --git a/nixl/src/nvidia/sdk.rs b/nixl/src/nvidia/sdk.rs new file mode 100644 index 00000000..fb943c44 --- /dev/null +++ b/nixl/src/nvidia/sdk.rs @@ -0,0 +1,26 @@ +//! Private interface to the NVIDIA client and its registered host windows. + +#[cxx::bridge(namespace = "rc::cuobject")] +pub(super) mod ffi { + // SAFETY: every mutable view borrows its pinned window. An outstanding + // token excludes host access until the SDK confirms its release. + unsafe extern "C++" { + include!("native/cuobject.h"); + type Client; + type NativeWindow; + + fn make_client() -> Result>; + fn register_window( + client: SharedPtr, + size: usize, + ) -> Result>; + fn writable(self: Pin<&mut NativeWindow>) -> Result<&mut [u8]>; + fn acquire(self: Pin<&mut NativeWindow>, length: usize, for_get: bool) -> Result<()>; + fn active_token(self: &NativeWindow) -> &[u8]; + fn release_token(self: Pin<&mut NativeWindow>) -> Result<()>; + } +} + +// SAFETY: transferring ownership between workers neither moves the mapping nor +// exposes it twice. The native client serializes SDK calls shared by windows. +unsafe impl Send for ffi::NativeWindow {} diff --git a/nixl/src/pool.rs b/nixl/src/pool.rs index 5dd296e4..b77fc046 100644 --- a/nixl/src/pool.rs +++ b/nixl/src/pool.rs @@ -11,7 +11,7 @@ pub(crate) const WINDOW: usize = rc_s3::multipart::DEFAULT_PART_SIZE as usize; const SMALL_WINDOW: usize = 1024 * 1024; const WINDOWS_PER_POOL: usize = 2; static AGENTS: Semaphore = Semaphore::const_new(8); -static QUARANTINE: Mutex> = Mutex::new(Vec::new()); +static QUARANTINE: Mutex> = Mutex::new(Vec::new()); #[derive(Default)] pub(crate) struct Pools { @@ -135,26 +135,23 @@ impl Window { len: usize, headers: &mut HeaderMap, ) -> Result { - let transfer = match self.buffer.as_ref().expect("owned window") { + let mut exposed = Exposed(Some(self)); + let buffer = exposed.window_mut().buffer.as_mut().expect("owned window"); + let result = match buffer { Buffer::Nixl { chunk, agent, metadata, - } => { - crate::wire::bind(headers, agent, metadata, chunk.addr(), len)?; - Transfer::Nixl(self) - } + } => crate::wire::bind(headers, agent, metadata, chunk.addr(), len), #[cfg(feature = "cuobject")] - Buffer::CuObject(_) => { - Transfer::CuObject(crate::nvidia::Exposure::try_new(self, |window| { - let Some(Buffer::CuObject(buffer)) = window.buffer.as_ref() else { - unreachable!("cuObject window") - }; - buffer.describe(_method, len, headers) - })?) - } + Buffer::CuObject(buffer) => buffer.describe(_method, len, headers), }; - Ok(Exposed(Some(transfer))) + if let Err(error) = result { + // The token has not left this process. Release it before reuse. + exposed.finished()?; + return Err(error); + } + Ok(exposed) } } @@ -171,43 +168,28 @@ impl Drop for Window { } } -enum Transfer { - Nixl(Window), - #[cfg(feature = "cuobject")] - CuObject(crate::nvidia::Exposure), -} - -impl Transfer { - fn window(&self) -> &Window { - match self { - Self::Nixl(window) => window, - #[cfg(feature = "cuobject")] - Self::CuObject(transfer) => transfer.borrow_owner(), - } - } - fn finished(self) -> Window { - match self { - Self::Nixl(window) => window, - #[cfg(feature = "cuobject")] - Self::CuObject(transfer) => transfer.into_owner(), - } +pub(crate) struct Exposed(Option); +impl Exposed { + fn window_mut(&mut self) -> &mut Window { + self.0.as_mut().expect("owned transfer") } -} -pub(crate) struct Exposed(Option); -impl Exposed { - pub(crate) fn finished(mut self) -> Window { - self.0.take().expect("owned transfer").finished() + pub(crate) fn finished(mut self) -> Result { + #[cfg(feature = "cuobject")] + if let Some(Buffer::CuObject(host)) = self.window_mut().buffer.as_mut() { + host.release_token()?; + } + Ok(self.0.take().expect("owned transfer")) } } impl Drop for Exposed { fn drop(&mut self) { - if let Some(transfer) = self.0.take() { - transfer.window().pool.lost.send_modify(|lost| *lost += 1); + if let Some(window) = self.0.take() { + window.pool.lost.send_modify(|lost| *lost += 1); QUARANTINE .lock() .unwrap_or_else(|e| e.into_inner()) - .push(transfer); + .push(window); } } } @@ -232,8 +214,15 @@ mod tests { #[cfg(feature = "cuobject")] { let mut exposed = exposed; - let release = match exposed.0.as_mut() { - Some(Transfer::CuObject(offer)) => Some(offer.observe_token_release()), + let release = match exposed.window_mut().buffer.as_mut() { + Some(Buffer::CuObject(host)) => { + assert!(host.writable().is_err()); + assert!( + host.describe(&Method::GET, 1, &mut HeaderMap::new()) + .is_err() + ); + Some(host.releases.clone()) + } _ => None, }; (exposed, release) @@ -260,7 +249,7 @@ mod tests { observe(first.expose(&Method::GET, 32, &mut headers).unwrap()); #[cfg(feature = "cuobject")] if backend == RdmaBackend::CuObject { - assert!(headers[cuobject::TOKEN_HEADER].is_sensitive()); + assert!(headers[crate::nvidia::TOKEN_HEADER].is_sensitive()); } let exchanging = |exposed: Exposed| async move { std::future::pending::<()>().await; @@ -291,11 +280,11 @@ mod tests { if backend == RdmaBackend::CuObject { let retained = QUARANTINE.lock().unwrap(); for advertised in [ - &headers[cuobject::TOKEN_HEADER], - &put_headers[cuobject::TOKEN_HEADER], + &headers[crate::nvidia::TOKEN_HEADER], + &put_headers[crate::nvidia::TOKEN_HEADER], ] { - assert!(retained.iter().any(|transfer| matches!(transfer, Transfer::CuObject(offer) - if Arc::ptr_eq(&offer.borrow_owner().pool, &old) && offer.holds_token(advertised)))); + assert!(retained.iter().any(|window| Arc::ptr_eq(&window.pool, &old) + && matches!(&window.buffer, Some(Buffer::CuObject(host)) if host.holds_token(advertised)))); } } let replacement = pools.reserve(32).await.unwrap(); @@ -306,7 +295,7 @@ mod tests { .expose(&Method::GET, 32, &mut HeaderMap::new()) .unwrap(), ); - let returned = completed.finished(); + let returned = completed.finished().unwrap(); if let Some(count) = &completed_releases { assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 1); } diff --git a/nixl/src/transport.rs b/nixl/src/transport.rs index 27b26a93..96697f64 100644 --- a/nixl/src/transport.rs +++ b/nixl/src/transport.rs @@ -58,12 +58,12 @@ impl Transport { match self.control.execute_registered(request).await { Ok(RegisteredControlResponse::Response(response)) => Ok((response, exposed)), Ok(RegisteredControlResponse::RejectedBeforeDma(error)) => { - drop(exposed.finished()); + drop(exposed.finished().map_err(rejected)?); Err(rejected(error)) } Err(error @ Error::RequestRejected(_)) => { // ControlExecutor rejected the request locally before sending it. - drop(exposed.finished()); + drop(exposed.finished().map_err(rejected)?); Err(unavailable(error)) } Err(error) => Err(unknown(error)), diff --git a/nixl/src/transport/download.rs b/nixl/src/transport/download.rs index 790dab86..efbf103a 100644 --- a/nixl/src/transport/download.rs +++ b/nixl/src/transport/download.rs @@ -81,7 +81,7 @@ impl Transport { ))); } wire::receipt(expected, &response.headers, len as u64).map_err(rejected)?; - let mut window = exposed.finished(); + let mut window = exposed.finished().map_err(rejected)?; if wire::field(&response.headers, "content-length") .map_err(rejected)? .is_some_and(|value| value != "0") diff --git a/nixl/src/transport/upload.rs b/nixl/src/transport/upload.rs index 7906699e..f0af725f 100644 --- a/nixl/src/transport/upload.rs +++ b/nixl/src/transport/upload.rs @@ -149,7 +149,7 @@ impl Transport { return Ok(None); } wire::receipt(StatusCode::OK, &response.headers, len as u64).map_err(unknown)?; - drop(exposed.finished()); + drop(exposed.finished().map_err(rejected)?); let etag = wire::field(&response.headers, "etag") .map_err(rejected)? .filter(|e| !e.is_empty()) diff --git a/nixl/src/wire/native_test.rs b/nixl/src/wire/native_test.rs index 00576801..b3f5dc6f 100644 --- a/nixl/src/wire/native_test.rs +++ b/nixl/src/wire/native_test.rs @@ -36,7 +36,7 @@ async fn rustfs_reads_and_writes_the_advertised_host_window() { .await .unwrap(); assert_eq!(written, 6); - let mut source = exposed.finished(); + let mut source = exposed.finished().unwrap(); source.finish_read(6).unwrap(); assert_eq!(source.received().unwrap(), b"result"); } From d7142ac8bd26c919ab47766ac70b2f676ebab3a3 Mon Sep 17 00:00:00 2001 From: gatewayj <835269233@qq.com> Date: Sun, 22 Nov 2026 01:03:19 +0800 Subject: [PATCH 05/13] fix(transfer): size registered windows and release idle siblings --- nixl/src/pool.rs | 53 ++++++++++++++++++++++++++++++++++++------------ 1 file changed, 40 insertions(+), 13 deletions(-) diff --git a/nixl/src/pool.rs b/nixl/src/pool.rs index b77fc046..888543e1 100644 --- a/nixl/src/pool.rs +++ b/nixl/src/pool.rs @@ -11,7 +11,14 @@ pub(crate) const WINDOW: usize = rc_s3::multipart::DEFAULT_PART_SIZE as usize; const SMALL_WINDOW: usize = 1024 * 1024; const WINDOWS_PER_POOL: usize = 2; static AGENTS: Semaphore = Semaphore::const_new(8); -static QUARANTINE: Mutex> = Mutex::new(Vec::new()); +// Keep the exposed registration and its budget, so the retired pool can free its idle buffers. +type Budget = Arc>; +static QUARANTINE: Mutex> = Mutex::new(Vec::new()); + +fn window_size(required: u64) -> usize { + let required = required.clamp(SMALL_WINDOW as u64, WINDOW as u64) as usize; + required.next_power_of_two().min(WINDOW) +} #[derive(Default)] pub(crate) struct Pools { @@ -28,11 +35,7 @@ impl Pools { } pub(crate) async fn reserve(&self, required: u64) -> Result { - let size = if required <= SMALL_WINDOW as u64 { - SMALL_WINDOW - } else { - WINDOW - }; + let size = window_size(required); loop { let pool = { let mut active = self.active.lock().await; @@ -64,7 +67,7 @@ struct Pool { free: Mutex>, available: Semaphore, lost: watch::Sender, - _budget: SemaphorePermit<'static>, + budget: Budget, } impl Pool { @@ -78,7 +81,7 @@ impl Pool { free: Mutex::new(buffers), available: Semaphore::new(WINDOWS_PER_POOL), lost: watch::Sender::new(0), - _budget: budget, + budget: Arc::new(budget), })) } @@ -184,12 +187,13 @@ impl Exposed { } impl Drop for Exposed { fn drop(&mut self) { - if let Some(window) = self.0.take() { + if let Some(mut window) = self.0.take() { + let buffer = window.buffer.take().expect("owned transfer"); window.pool.lost.send_modify(|lost| *lost += 1); QUARANTINE .lock() .unwrap_or_else(|e| e.into_inner()) - .push(window); + .push((buffer, Arc::clone(&window.pool.budget))); } } } @@ -198,6 +202,14 @@ impl Drop for Exposed { mod tests { use super::*; + #[test] + fn registrations_use_a_bounded_size_class() { + assert_eq!(window_size(0), SMALL_WINDOW); + assert_eq!(window_size(SMALL_WINDOW as u64), SMALL_WINDOW); + assert_eq!(window_size(3 * SMALL_WINDOW as u64), 4 * SMALL_WINDOW); + assert_eq!(window_size(u64::MAX), WINDOW); + } + #[tokio::test] async fn uncertain_windows_wake_waiters_and_cannot_be_reissued() { check_window_lifetime(RdmaBackend::Nixl).await; @@ -283,11 +295,12 @@ mod tests { &headers[crate::nvidia::TOKEN_HEADER], &put_headers[crate::nvidia::TOKEN_HEADER], ] { - assert!(retained.iter().any(|window| Arc::ptr_eq(&window.pool, &old) - && matches!(&window.buffer, Some(Buffer::CuObject(host)) if host.holds_token(advertised)))); + assert!(retained.iter().any(|(buffer, budget)| Arc::ptr_eq(budget, &old.budget) + && matches!(buffer, Buffer::CuObject(host) if host.holds_token(advertised)))); } } - let replacement = pools.reserve(32).await.unwrap(); + let replacement = pools.reserve(3 * SMALL_WINDOW as u64).await.unwrap(); + assert_eq!(replacement.pool.size, 4 * SMALL_WINDOW); assert!(!Arc::ptr_eq(&old, &replacement.pool)); let fresh_pool = replacement.pool.clone(); let (completed, completed_releases) = observe( @@ -316,5 +329,19 @@ mod tests { } assert_eq!(fresh_pool.available.available_permits(), WINDOWS_PER_POOL); assert_eq!(old.available.available_permits(), 0); + + // Retiring a pool with one uncertain transfer must free its idle sibling. + let window = pools.reserve(32).await.unwrap(); + let pool = Arc::downgrade(&fresh_pool); + let budget = Arc::downgrade(&fresh_pool.budget); + drop( + window + .expose(&Method::GET, 32, &mut HeaderMap::new()) + .unwrap(), + ); + drop(fresh_pool); + drop(pools); + assert!(pool.upgrade().is_none()); + assert!(budget.upgrade().is_some()); } } From 0a3979a3ce3d0f38081ec3fbded84c08492ad27c Mon Sep 17 00:00:00 2001 From: gatewayj <835269233@qq.com> Date: Sun, 22 Nov 2026 01:10:16 +0800 Subject: [PATCH 06/13] docs(rdma): describe window sizes and registration lifetime --- docs/rdma-build.md | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/docs/rdma-build.md b/docs/rdma-build.md index f2b3666e..cc8ed1dc 100644 --- a/docs/rdma-build.md +++ b/docs/rdma-build.md @@ -59,9 +59,10 @@ unavailable. The default `http` policy transfers the payload through S3. File uploads use positional reads directly into two reusable registered windows. Each completed part frees a window for the next part, and S3 receives -the completion list in part-number order. For transfers of up to 1 MiB, the client can register two 1 MiB -windows. Larger transfers use 64 MiB windows, which also serve subsequent -small requests on the same client. File downloads write directly into the temporary +the completion list in part-number order. A new pool sizes each window to the +next power of two that fits the requested part or range, with a 1 MiB minimum +and a 64 MiB maximum. For example, a 4 MiB range registers two 4 MiB windows. +A client can reuse its existing larger pool for subsequent small requests. File downloads write directly into the temporary destination file. A range GET for the next window can proceed while the previous window is being written. All requests keep the caller's version selector. Each GET uses `If-Match` and checks the version from HEAD before delivering that range. Downloads publish the temporary file @@ -73,7 +74,9 @@ error document and no RDMA response headers. An ambiguous response, a missing receipt, cancellation or timeout retains the token and window until the process exits. When both windows are unavailable for this reason, waiting operations use a -fresh pool within the process registration budget. +fresh pool within the process registration budget. Retiring a cuObject pool +releases its idle registrations. Each quarantined window keeps its own +registration and the pool's budget reservation. RustFS can interpret a declined external PUT as an ordinary empty PUT. The client uploads nonempty objects into unpublished multipart parts and From f809d60facd1222a0d571441f650849f40172cce Mon Sep 17 00:00:00 2001 From: jhw Date: Sun, 22 Nov 2026 09:33:17 +0800 Subject: [PATCH 07/13] refactor(rdma): isolate cuObject client bindings and window ownership --- .github/workflows/nixl.yml | 2 + AGENTS.md | 4 +- docs/ADR/0001-object-data-transport.md | 3 +- docs/rdma-build.md | 2 +- nixl/Cargo.lock | 18 +++++- nixl/Cargo.toml | 9 ++- nixl/cuobject-client-sys/Cargo.toml | 18 ++++++ nixl/{ => cuobject-client-sys}/build.rs | 12 ++-- .../native/cuobject.cc | 0 .../native/cuobject.h | 0 nixl/cuobject-client-sys/src/lib.rs | 13 +++++ .../nvidia => cuobject-client-sys/src}/sdk.rs | 0 nixl/cuobject-client/Cargo.toml | 14 +++++ nixl/cuobject-client/src/lib.rs | 58 +++++++++++++++++++ nixl/src/main.rs | 3 +- nixl/src/nvidia.rs | 33 ++++------- 16 files changed, 146 insertions(+), 43 deletions(-) create mode 100644 nixl/cuobject-client-sys/Cargo.toml rename nixl/{ => cuobject-client-sys}/build.rs (82%) rename nixl/{ => cuobject-client-sys}/native/cuobject.cc (100%) rename nixl/{ => cuobject-client-sys}/native/cuobject.h (100%) create mode 100644 nixl/cuobject-client-sys/src/lib.rs rename nixl/{src/nvidia => cuobject-client-sys/src}/sdk.rs (100%) create mode 100644 nixl/cuobject-client/Cargo.toml create mode 100644 nixl/cuobject-client/src/lib.rs diff --git a/.github/workflows/nixl.yml b/.github/workflows/nixl.yml index 71e21b66..d4f7440d 100644 --- a/.github/workflows/nixl.yml +++ b/.github/workflows/nixl.yml @@ -32,6 +32,8 @@ jobs: - uses: Swatinem/rust-cache@e18b497796c12c097a38f9edb9d0641fb99eee32 # v2 with: workspaces: nixl + - name: Check the cuObject crates without the NVIDIA SDK + run: cargo check --locked --manifest-path nixl/Cargo.toml -p rustfs-cuobject-client -p rustfs-cuobject-client-sys - name: Install native build tools run: | echo "NIXL_PREFIX=$RUNNER_TEMP/nixl" >> "$GITHUB_ENV" diff --git a/AGENTS.md b/AGENTS.md index 0b5296b4..fdb9927f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -104,9 +104,9 @@ Modifying protected files requires: - Violation: may cause panic 3. **Using `unsafe` outside the private NVIDIA SDK bridge** - - Only the private bridge in `nixl/src/nvidia/sdk.rs`, behind the `cuobject` feature, may declare the C++ interface and the thread ownership of its opaque window. Keep handwritten Rust operations outside this exception. + - Only the private bridge in `nixl/cuobject-client-sys/src/sdk.rs`, enabled by the native executable’s `cuobject` feature, may declare the C++ interface and the thread ownership of its opaque window. Keep handwritten Rust operations outside this exception. - Native host slices require an exclusive window. Once a token is exposed, retain it with its registration until confirmed completion or proof that DMA never started. Quarantine an uncertain exchange or failed token release for the life of the process. - - Keep the lint exception on the bridge. Native builds without `cuobject` must retain `forbid(unsafe_code)`. + - Keep the lint exception on the bridge. The native executable and the `rustfs-cuobject-client` library must retain `forbid(unsafe_code)`. 4. **Printing credentials in logs/errors** - Includes: access_key, secret_key, Authorization headers diff --git a/docs/ADR/0001-object-data-transport.md b/docs/ADR/0001-object-data-transport.md index dbceea1f..8f8480b4 100644 --- a/docs/ADR/0001-object-data-transport.md +++ b/docs/ADR/0001-object-data-transport.md @@ -17,8 +17,7 @@ The common launcher preserves command dispatch, output, exit codes, and the existing worker-thread configuration. The NIXL backend supplies agent metadata and a registered buffer description. -The NVIDIA cuObject backend uses a private CXX bridge to register host memory with -`cuObjClient` and acquire a direction-specific token for each transfer. The window can be reused after +The NVIDIA backend uses `rustfs-cuobject-client` for registered windows and transfer tokens. Its dependency `rustfs-cuobject-client-sys` builds the C++ bridge and links the NVIDIA client SDK. The window can be reused after a verified receipt or proof that DMA never started. An uncertain transfer retains both resources within the process registration budget. Both use the host-owned `ControlExecutor`. The S3 client signs and sends a bodyless HTTPS request on the shared S3 HTTP client using the alias timeout policy. It returns the status and headers directly, diff --git a/docs/rdma-build.md b/docs/rdma-build.md index cc8ed1dc..c4235611 100644 --- a/docs/rdma-build.md +++ b/docs/rdma-build.md @@ -34,7 +34,7 @@ to the same executable, install the NVIDIA cuObject **client** SDK, cuFile development libraries, libibverbs development headers and CUDA headers for the target architecture. Set `CUOBJCLIENT_ROOT` to the SDK prefix and `CUDA_HOME` to the CUDA toolkit. -The CLI builds its C++17 adapter against `cuobjclient.h` and links directly to the NVIDIA SDK. +The `rustfs-cuobject-client-sys` crate builds the C++17 adapter against `cuobjclient.h` and links the NVIDIA SDK. The CLI accesses registered windows and tokens through `rustfs-cuobject-client`. The SDK's `libcuobjclient`, `libcufile` and RDMA plugin must be available at runtime. Set `CUOBJ_ENV_PATH_JSON` to the NVIDIA client configuration that selects the application RDMA device. diff --git a/nixl/Cargo.lock b/nixl/Cargo.lock index b4ac96e1..c1cb7a7e 100644 --- a/nixl/Cargo.lock +++ b/nixl/Cargo.lock @@ -2998,17 +2998,31 @@ version = "0.1.0" dependencies = [ "async-trait", "base64 0.22.1", - "cxx", - "cxx-build", "getrandom 0.4.3", "http", "rc-core", "rc-s3", "rustfs-cli", + "rustfs-cuobject-client", "rustfs-nixl", "tokio", ] +[[package]] +name = "rustfs-cuobject-client" +version = "0.1.0" +dependencies = [ + "rustfs-cuobject-client-sys", +] + +[[package]] +name = "rustfs-cuobject-client-sys" +version = "0.1.0" +dependencies = [ + "cxx", + "cxx-build", +] + [[package]] name = "rustfs-nixl" version = "1.0.5" diff --git a/nixl/Cargo.toml b/nixl/Cargo.toml index e79a208d..5dce38e9 100644 --- a/nixl/Cargo.toml +++ b/nixl/Cargo.toml @@ -8,16 +8,18 @@ publish = false [workspace] resolver = "3" +members = ["cuobject-client", "cuobject-client-sys"] +default-members = ["."] [[bin]] name = "rc" path = "src/main.rs" [features] -cuobject = ["dep:cxx", "dep:cxx-build"] +cuobject = ["dep:rustfs-cuobject-client"] [dependencies] -cxx = { version = "1", optional = true } +rustfs-cuobject-client = { path = "cuobject-client", features = ["client"], optional = true } rustfs-cli = { path = "../crates/cli" } rc-core = { path = "../crates/core" } rc-s3 = { path = "../crates/s3" } @@ -27,6 +29,3 @@ base64 = "0.22" getrandom = "0.4" http = "1" tokio = { version = "1", features = ["io-util", "sync", "time"] } - -[build-dependencies] -cxx-build = { version = "1", optional = true } diff --git a/nixl/cuobject-client-sys/Cargo.toml b/nixl/cuobject-client-sys/Cargo.toml new file mode 100644 index 00000000..03d58297 --- /dev/null +++ b/nixl/cuobject-client-sys/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "rustfs-cuobject-client-sys" +version = "0.1.0" +edition = "2024" +rust-version = "1.99.0" +license = "MIT OR Apache-2.0" +publish = false +description = "Native bindings to the NVIDIA cuObject client SDK" +links = "cuobjclient" + +[features] +client = ["dep:cxx", "dep:cxx-build"] + +[dependencies] +cxx = { version = "1", optional = true } + +[build-dependencies] +cxx-build = { version = "1", optional = true } diff --git a/nixl/build.rs b/nixl/cuobject-client-sys/build.rs similarity index 82% rename from nixl/build.rs rename to nixl/cuobject-client-sys/build.rs index 8fbad863..60d2cddd 100644 --- a/nixl/build.rs +++ b/nixl/cuobject-client-sys/build.rs @@ -1,20 +1,16 @@ fn main() { - #[cfg(feature = "cuobject")] + #[cfg(feature = "client")] build_cuobject(); } -#[cfg(feature = "cuobject")] +#[cfg(feature = "client")] fn build_cuobject() { use std::{env, path::PathBuf}; for name in ["CUOBJCLIENT_ROOT", "CUDA_HOME"] { println!("cargo:rerun-if-env-changed={name}"); } - for file in [ - "src/nvidia/sdk.rs", - "native/cuobject.h", - "native/cuobject.cc", - ] { + for file in ["src/sdk.rs", "native/cuobject.h", "native/cuobject.cc"] { println!("cargo:rerun-if-changed={file}"); } let cuda = env::var_os("CUDA_HOME") @@ -23,7 +19,7 @@ fn build_cuobject() { let sdk = env::var_os("CUOBJCLIENT_ROOT") .map(PathBuf::from) .unwrap_or_else(|| cuda.clone()); - cxx_build::bridge("src/nvidia/sdk.rs") + cxx_build::bridge("src/sdk.rs") .file("native/cuobject.cc") .include(".") .include(sdk.join("include")) diff --git a/nixl/native/cuobject.cc b/nixl/cuobject-client-sys/native/cuobject.cc similarity index 100% rename from nixl/native/cuobject.cc rename to nixl/cuobject-client-sys/native/cuobject.cc diff --git a/nixl/native/cuobject.h b/nixl/cuobject-client-sys/native/cuobject.h similarity index 100% rename from nixl/native/cuobject.h rename to nixl/cuobject-client-sys/native/cuobject.h diff --git a/nixl/cuobject-client-sys/src/lib.rs b/nixl/cuobject-client-sys/src/lib.rs new file mode 100644 index 00000000..afa7af8a --- /dev/null +++ b/nixl/cuobject-client-sys/src/lib.rs @@ -0,0 +1,13 @@ +//! Native bindings for NVIDIA cuObject client registrations. +#![cfg(feature = "client")] +#![deny(unsafe_code)] + +#[expect( + unsafe_code, + reason = "NVIDIA SDK declarations and native window thread ownership" +)] +mod sdk; + +pub use sdk::ffi::{make_client, register_window}; +pub type ClientHandle = cxx::SharedPtr; +pub type WindowHandle = cxx::UniquePtr; diff --git a/nixl/src/nvidia/sdk.rs b/nixl/cuobject-client-sys/src/sdk.rs similarity index 100% rename from nixl/src/nvidia/sdk.rs rename to nixl/cuobject-client-sys/src/sdk.rs diff --git a/nixl/cuobject-client/Cargo.toml b/nixl/cuobject-client/Cargo.toml new file mode 100644 index 00000000..8fad34f5 --- /dev/null +++ b/nixl/cuobject-client/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "rustfs-cuobject-client" +version = "0.1.0" +edition = "2024" +rust-version = "1.99.0" +license = "MIT OR Apache-2.0" +publish = false +description = "NVIDIA cuObject client registrations and transfer tokens" + +[features] +client = ["dep:rustfs-cuobject-client-sys"] + +[dependencies] +rustfs-cuobject-client-sys = { path = "../cuobject-client-sys", features = ["client"], optional = true } diff --git a/nixl/cuobject-client/src/lib.rs b/nixl/cuobject-client/src/lib.rs new file mode 100644 index 00000000..825992e5 --- /dev/null +++ b/nixl/cuobject-client/src/lib.rs @@ -0,0 +1,58 @@ +//! Registered host windows for NVIDIA cuObject transfers. +#![cfg(feature = "client")] +#![forbid(unsafe_code)] + +use rustfs_cuobject_client_sys as sys; +use std::io; + +/// A native client shared by the windows it registers. +pub struct Client(sys::ClientHandle); + +impl Client { + pub fn open() -> io::Result { + sys::make_client().map(Self).map_err(io::Error::other) + } + + /// Registers a host mapping that keeps its native client alive. + pub fn register(&self, bytes: usize) -> io::Result { + sys::register_window(self.0.clone(), bytes) + .map(Window) + .map_err(io::Error::other) + } +} + +/// The operation for which a remote endpoint can use a token. +pub enum Operation { + Get, + Put, +} + +/// A registered host buffer. Dropping a window with an active or uncertain +/// token keeps its native mapping and registration alive. +pub struct Window(sys::WindowHandle); + +impl Window { + /// Borrows the registered bytes when the window has no active token. + pub fn writable(&mut self) -> io::Result<&mut [u8]> { + self.0.pin_mut().writable().map_err(io::Error::other) + } + + /// Exposes the first `length` bytes for one transfer and excludes host access. + pub fn acquire_token(&mut self, operation: Operation, length: usize) -> io::Result<&[u8]> { + self.0 + .pin_mut() + .acquire(length, matches!(operation, Operation::Get)) + .map_err(io::Error::other)?; + Ok(self.active_token()) + } + + pub fn active_token(&self) -> &[u8] { + self.0.active_token() + } + + /// Releases the token after confirmed completion or proof that DMA never + /// started. An uncertain exchange must keep the token and window together. + pub fn release_after_completion(&mut self) -> io::Result<()> { + self.0.pin_mut().release_token().map_err(io::Error::other) + } +} diff --git a/nixl/src/main.rs b/nixl/src/main.rs index 37800f04..f71db3ea 100644 --- a/nixl/src/main.rs +++ b/nixl/src/main.rs @@ -1,6 +1,5 @@ //! rc with native S3-over-RDMA providers. -#![deny(unsafe_code)] -#![cfg_attr(not(feature = "cuobject"), forbid(unsafe_code))] +#![forbid(unsafe_code)] mod buffer; #[cfg(feature = "cuobject")] diff --git a/nixl/src/nvidia.rs b/nixl/src/nvidia.rs index 9121b0a2..8ffd039a 100644 --- a/nixl/src/nvidia.rs +++ b/nixl/src/nvidia.rs @@ -3,25 +3,19 @@ use crate::buffer::Buffer; use http::{HeaderMap, HeaderValue, Method}; use rc_core::{Error, Result}; +use rustfs_cuobject_client::{Client, Operation, Window}; pub(super) const TOKEN_HEADER: &str = "x-amz-rdma-token"; -#[expect( - unsafe_code, - reason = "private SDK declarations and native window thread ownership" -)] -mod sdk; -use sdk::ffi; - -fn sdk_error(error: cxx::Exception) -> Error { +fn sdk_error(error: std::io::Error) -> Error { Error::General(format!("NVIDIA cuObject: {error}")) } pub(super) fn register(size: usize, count: usize) -> Result> { - let client = ffi::make_client().map_err(sdk_error)?; + let client = Client::open().map_err(sdk_error)?; (0..count) .map(|_| { - let raw = ffi::register_window(client.clone(), size).map_err(sdk_error)?; + let raw = client.register(size).map_err(sdk_error)?; Ok(Buffer::CuObject(HostBuffer { raw, #[cfg(test)] @@ -32,14 +26,14 @@ pub(super) fn register(size: usize, count: usize) -> Result> { } pub(super) struct HostBuffer { - raw: cxx::UniquePtr, + raw: Window, #[cfg(test)] pub(super) releases: std::sync::Arc, } impl HostBuffer { pub(super) fn writable(&mut self) -> Result<&mut [u8]> { - self.raw.pin_mut().writable().map_err(sdk_error) + self.raw.writable().map_err(sdk_error) } pub(super) fn describe( @@ -48,16 +42,13 @@ impl HostBuffer { len: usize, headers: &mut HeaderMap, ) -> Result<()> { - let for_get = match *method { - Method::GET => true, - Method::PUT => false, + let operation = match *method { + Method::GET => Operation::Get, + Method::PUT => Operation::Put, _ => return Err(Error::General("Unsupported cuObject operation".into())), }; - self.raw - .pin_mut() - .acquire(len, for_get) - .map_err(sdk_error)?; - let mut value = HeaderValue::from_bytes(self.raw.active_token()) + let token = self.raw.acquire_token(operation, len).map_err(sdk_error)?; + let mut value = HeaderValue::from_bytes(token) .map_err(|_| Error::General("Invalid NVIDIA cuObject token".into()))?; value.set_sensitive(true); headers.insert(TOKEN_HEADER, value); @@ -67,7 +58,7 @@ impl HostBuffer { pub(super) fn release_token(&mut self) -> Result<()> { #[cfg(test)] let active = !self.raw.active_token().is_empty(); - self.raw.pin_mut().release_token().map_err(sdk_error)?; + self.raw.release_after_completion().map_err(sdk_error)?; #[cfg(test)] if active { self.releases From 10f091c3d9255f8813d24323a64328ab1e908e9e Mon Sep 17 00:00:00 2001 From: GatewayJ <835269233@qq.com> Date: Sun, 22 Nov 2026 10:40:47 +0800 Subject: [PATCH 08/13] perf(rdma): fetch adjacent object ranges concurrently --- nixl/src/pool.rs | 3 - nixl/src/transport/download.rs | 111 +++++++++++++++++++++++---------- nixl/src/transport/tests.rs | 73 ++++++++++++++++++++++ 3 files changed, 152 insertions(+), 35 deletions(-) diff --git a/nixl/src/pool.rs b/nixl/src/pool.rs index 888543e1..f3bad5bd 100644 --- a/nixl/src/pool.rs +++ b/nixl/src/pool.rs @@ -129,9 +129,6 @@ impl Window { Ok(()) } - pub(crate) fn len(&self) -> usize { - self.len - } pub(crate) fn expose( self, _method: &Method, diff --git a/nixl/src/transport/download.rs b/nixl/src/transport/download.rs index efbf103a..153d635c 100644 --- a/nixl/src/transport/download.rs +++ b/nixl/src/transport/download.rs @@ -5,6 +5,33 @@ pub(super) enum Sink<'a> { Writer(&'a mut (dyn AsyncWrite + Send + Unpin)), } +impl Sink<'_> { + async fn write_range( + &mut self, + mut window: Window, + offset: u64, + checksum: Option<&mut PayloadChecksumVerifier>, + ) -> Result<()> { + if let Some(checksum) = checksum { + checksum.update(window.received()?); + } + match self { + Self::Writer(writer) => writer.write_all(window.received()?).await?, + Self::File(file) => { + use std::os::unix::fs::FileExt; + let file = file.clone(); + tokio::task::spawn_blocking(move || { + file.write_all_at(window.received()?, offset)?; + Ok::<_, Error>(()) + }) + .await + .map_err(|_| Error::General("RDMA file write was interrupted".into()))??; + } + } + Ok(()) + } +} + struct Selection<'a> { path: &'a RemotePath, requested_version: Option<&'a str>, @@ -33,6 +60,7 @@ impl Transport { offset: u64, len: usize, ranged: bool, + window: Window, ) -> DataTransportResult { let mut headers = HeaderMap::new(); headers.insert("if-match", selection.etag.clone()); @@ -46,7 +74,6 @@ impl Transport { } else { StatusCode::OK }; - let window = self.pools.reserve(len as u64).await.map_err(unavailable)?; // An empty object still requires a nonempty descriptor. let exposed = window .expose(&Method::GET, len.max(1), &mut headers) @@ -168,44 +195,64 @@ impl Transport { observed_version, }; let ranged = length > 0 && (request.max_bytes.is_some() || length > WINDOW as u64); - let first = length.min(WINDOW as u64) as usize; - let mut current = self.fetch(&selection, 0, first, ranged).await?; - let mut end = first as u64; let mut checksum = PayloadChecksumVerifier::new(&head.headers).map_err(rejected)?; + let mut offset = 0; loop { - let write = async { - if length == total { - checksum.update(current.received()?); + let first = (length - offset).min(WINDOW as u64); + let next = offset + first; + let second = (length - next).min(WINDOW as u64); + // Reserve the earlier range first. It can finish and release its window + // even if other downloads or a quarantined window leave only one slot. + let window = self.pools.reserve(first).await.map_err(|e| { + if offset == 0 { + unavailable(e) + } else { + rejected(e) } - let offset = end - current.len() as u64; - match &mut target { - Sink::Writer(writer) => writer.write_all(current.received()?).await?, - Sink::File(file) => { - use std::os::unix::fs::FileExt; - let file = file.clone(); - tokio::task::spawn_blocking(move || { - file.write_all_at(current.received()?, offset)?; - Ok::<_, Error>(()) - }) - .await - .map_err(|_| Error::General("RDMA file write was interrupted".into()))??; - } - } - (request.on_progress)(end, Some(length)); - Ok::<_, Error>(()) + })?; + let publish_first = async { + let window = self + .fetch(&selection, offset, first as usize, ranged, window) + .await + .map_err(|mut error| { + if offset != 0 { + error.state = DataTransferState::ConfirmedFailure; + } + error + })?; + target + .write_range(window, offset, (length == total).then_some(&mut checksum)) + .await + .map_err(rejected)?; + (request.on_progress)(next, Some(length)); + Ok(()) }; - if end == length { - write.await.map_err(rejected)?; + if second == 0 { + publish_first.await?; break; } - let size = (length - end).min(WINDOW as u64) as usize; - let (written, next) = tokio::join!(write, self.fetch(&selection, end, size, true)); - written.map_err(rejected)?; - current = next.map_err(|mut err| { - err.state = DataTransferState::ConfirmedFailure; - err + let fetch_second = async { + let window = self.pools.reserve(second).await.map_err(unavailable)?; + self.fetch(&selection, next, second as usize, true, window) + .await + }; + // Settle both control exchanges even when one fails. Only the ordered + // consumer updates the checksum, writes bytes and reports progress. + let (first_result, second_result) = tokio::join!(publish_first, fetch_second); + first_result?; + let window = second_result.map_err(|mut error| { + error.state = DataTransferState::ConfirmedFailure; + error })?; - end += size as u64; + target + .write_range(window, next, (length == total).then_some(&mut checksum)) + .await + .map_err(rejected)?; + offset = next + second; + (request.on_progress)(offset, Some(length)); + if offset == length { + break; + } } if length == total { checksum.verify(&head.headers).map_err(rejected)?; diff --git a/nixl/src/transport/tests.rs b/nixl/src/transport/tests.rs index 34bfee0f..908044ad 100644 --- a/nixl/src/transport/tests.rs +++ b/nixl/src/transport/tests.rs @@ -230,3 +230,76 @@ async fn rustfs_declines_a_stale_conditional_get_before_dma() { } } } + +#[tokio::test] +async fn large_get_submits_both_ranges_and_publishes_in_order() { + struct Ranges(tokio::sync::Notify); + + #[async_trait] + impl ControlExecutor for Ranges { + async fn execute_headers(&self, request: ControlRequest) -> Result { + let total = WINDOW + 19; + let mut headers = HeaderMap::new(); + headers.insert("etag", HeaderValue::from_static("\"immutable\"")); + if request.method == Method::HEAD { + headers.insert("content-length", HeaderValue::from(total)); + return Ok(ControlResponse { + status: StatusCode::OK, + headers, + }); + } + assert_eq!(request.headers["if-match"], "\"immutable\""); + let range = request.headers["range"] + .to_str() + .unwrap() + .strip_prefix("bytes=") + .unwrap(); + let (start, end) = range.split_once('-').unwrap(); + let (start, end): (usize, usize) = (start.parse().unwrap(), end.parse().unwrap()); + if start == 0 { + assert_eq!(end, WINDOW - 1); + tokio::time::timeout(std::time::Duration::from_secs(5), self.0.notified()) + .await + .expect("the second range must enter before the first completes"); + } else { + assert_eq!((start, end), (WINDOW, total - 1)); + self.0.notify_one(); + } + headers.insert( + "content-range", + format!("bytes {start}-{end}/{total}").parse().unwrap(), + ); + headers.insert("content-length", HeaderValue::from_static("0")); + headers.insert(RDMA_REPLY_HEADER, HeaderValue::from_static("206")); + headers.insert( + rustfs_nixl::RDMA_BYTES_TRANSFERRED_HEADER, + HeaderValue::from(end - start + 1), + ); + Ok(ControlResponse { + status: StatusCode::PARTIAL_CONTENT, + headers, + }) + } + } + + let transport = Factory(RdmaBackend::Nixl) + .create(Arc::new(Ranges(tokio::sync::Notify::new()))) + .unwrap(); + let mut progress = Vec::new(); + let total = WINDOW as u64 + 19; + let result = transport + .download( + DownloadRequest { + path: &RemotePath::new("local", "bucket", "key"), + options: &Default::default(), + max_bytes: None, + max_receive_bytes: total, + on_progress: &mut |written, _| progress.push(written), + }, + &mut tokio::io::sink(), + ) + .await + .unwrap(); + assert_eq!(result.bytes_transferred, total); + assert_eq!(progress, [WINDOW as u64, total]); +} From 0e162c685caeb2985575c3ccb919c5f5be6bb6f4 Mon Sep 17 00:00:00 2001 From: GatewayJ <835269233@qq.com> Date: Sun, 22 Nov 2026 10:44:49 +0800 Subject: [PATCH 09/13] docs(rdma): describe concurrent range verification --- docs/rdma-build.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/rdma-build.md b/docs/rdma-build.md index c4235611..ba34dab9 100644 --- a/docs/rdma-build.md +++ b/docs/rdma-build.md @@ -62,11 +62,13 @@ windows. Each completed part frees a window for the next part, and S3 receives the completion list in part-number order. A new pool sizes each window to the next power of two that fits the requested part or range, with a 1 MiB minimum and a 64 MiB maximum. For example, a 4 MiB range registers two 4 MiB windows. -A client can reuse its existing larger pool for subsequent small requests. File downloads write directly into the temporary -destination file. A range GET for the next window can proceed while the -previous window is being written. All requests keep the caller's version selector. Each GET uses -`If-Match` and checks the version from HEAD before delivering that range. Downloads publish the temporary file -after verifying the transfer count and any applicable object checksum. +A client can reuse its existing larger pool for subsequent small requests. +For large downloads, NIXL and cuObject issue up to two adjacent range GETs +concurrently. Each request uses the caller's version selector and `If-Match`. +The CLI checks each response against the version observed by HEAD and the requested range, +consumes the results in byte order, and writes directly to the destination +stream or temporary file. File downloads publish the temporary file after +verifying the transfer count and any applicable object checksum. A verified receipt releases the window. A local rejection before sending or an authenticated S3 `PreconditionFailed` response to an `If-Match` GET also releases it. For the latter, the client requires HTTP 412, a bounded S3 From 54e99529667a9818aa18d525aa1f3a735ce42eeb Mon Sep 17 00:00:00 2001 From: GatewayJ <835269233@qq.com> Date: Sun, 22 Nov 2026 10:49:38 +0800 Subject: [PATCH 10/13] test(rdma): check object checksum after out-of-order range reads --- nixl/src/transport/tests.rs | 66 ++++++++++++++++++++++++------------- 1 file changed, 43 insertions(+), 23 deletions(-) diff --git a/nixl/src/transport/tests.rs b/nixl/src/transport/tests.rs index 908044ad..5a7a02e3 100644 --- a/nixl/src/transport/tests.rs +++ b/nixl/src/transport/tests.rs @@ -233,7 +233,10 @@ async fn rustfs_declines_a_stale_conditional_get_before_dma() { #[tokio::test] async fn large_get_submits_both_ranges_and_publishes_in_order() { - struct Ranges(tokio::sync::Notify); + struct Ranges { + second: tokio::sync::Notify, + wrong_checksum: bool, + } #[async_trait] impl ControlExecutor for Ranges { @@ -243,6 +246,13 @@ async fn large_get_submits_both_ranges_and_publishes_in_order() { headers.insert("etag", HeaderValue::from_static("\"immutable\"")); if request.method == Method::HEAD { headers.insert("content-length", HeaderValue::from(total)); + if self.wrong_checksum { + // SHA-256 of the empty payload, while these two ranges are nonempty. + headers.insert( + "x-amz-checksum-sha256", + HeaderValue::from_static("47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU="), + ); + } return Ok(ControlResponse { status: StatusCode::OK, headers, @@ -258,12 +268,12 @@ async fn large_get_submits_both_ranges_and_publishes_in_order() { let (start, end): (usize, usize) = (start.parse().unwrap(), end.parse().unwrap()); if start == 0 { assert_eq!(end, WINDOW - 1); - tokio::time::timeout(std::time::Duration::from_secs(5), self.0.notified()) + tokio::time::timeout(std::time::Duration::from_secs(5), self.second.notified()) .await .expect("the second range must enter before the first completes"); } else { assert_eq!((start, end), (WINDOW, total - 1)); - self.0.notify_one(); + self.second.notify_one(); } headers.insert( "content-range", @@ -282,24 +292,34 @@ async fn large_get_submits_both_ranges_and_publishes_in_order() { } } - let transport = Factory(RdmaBackend::Nixl) - .create(Arc::new(Ranges(tokio::sync::Notify::new()))) - .unwrap(); - let mut progress = Vec::new(); - let total = WINDOW as u64 + 19; - let result = transport - .download( - DownloadRequest { - path: &RemotePath::new("local", "bucket", "key"), - options: &Default::default(), - max_bytes: None, - max_receive_bytes: total, - on_progress: &mut |written, _| progress.push(written), - }, - &mut tokio::io::sink(), - ) - .await - .unwrap(); - assert_eq!(result.bytes_transferred, total); - assert_eq!(progress, [WINDOW as u64, total]); + for wrong_checksum in [false, true] { + let transport = Factory(RdmaBackend::Nixl) + .create(Arc::new(Ranges { + second: tokio::sync::Notify::new(), + wrong_checksum, + })) + .unwrap(); + let mut progress = Vec::new(); + let total = WINDOW as u64 + 19; + let result = transport + .download( + DownloadRequest { + path: &RemotePath::new("local", "bucket", "key"), + options: &Default::default(), + max_bytes: None, + max_receive_bytes: total, + on_progress: &mut |written, _| progress.push(written), + }, + &mut tokio::io::sink(), + ) + .await; + if wrong_checksum { + assert!( + matches!(result, Err(error) if matches!(error.source.as_deref(), Some(Error::General(message)) if message.contains("checksum does not match"))) + ); + } else { + assert_eq!(result.unwrap().bytes_transferred, total); + } + assert_eq!(progress, [WINDOW as u64, total]); + } } From e2218c346a5b8ad4ab76e6012c690a998d7b1f8c Mon Sep 17 00:00:00 2001 From: GatewayJ <835269233@qq.com> Date: Sun, 22 Nov 2026 12:34:07 +0800 Subject: [PATCH 11/13] fix(rdma): preserve range outcomes and native registration budgets --- crates/s3/src/client.rs | 4 + crates/s3/src/data_transport.rs | 5 + docs/rdma-build.md | 6 +- nixl/cuobject-client-sys/native/cuobject.cc | 15 +- nixl/cuobject-client-sys/native/cuobject.h | 5 +- nixl/cuobject-client-sys/src/lib.rs | 1 + nixl/cuobject-client-sys/src/sdk.rs | 15 ++ nixl/cuobject-client/src/lib.rs | 11 +- nixl/src/buffer.rs | 9 +- nixl/src/main.rs | 2 +- nixl/src/nvidia.rs | 8 +- nixl/src/pool.rs | 7 +- nixl/src/transport.rs | 98 ++++++++++- nixl/src/transport/download.rs | 36 +++- nixl/src/transport/tests.rs | 183 +++++++++++++++++++- nixl/src/transport/upload.rs | 5 + 16 files changed, 377 insertions(+), 33 deletions(-) diff --git a/crates/s3/src/client.rs b/crates/s3/src/client.rs index 1039d210..ceaa508d 100644 --- a/crates/s3/src/client.rs +++ b/crates/s3/src/client.rs @@ -7786,6 +7786,10 @@ impl S3Client { /// External control exchanges retain the host client's TLS and signing policy. #[async_trait] impl ControlExecutor for S3Client { + fn endpoint(&self) -> Option<&str> { + Some(&self.alias.endpoint) + } + async fn execute_registered( &self, request: ControlRequest, diff --git a/crates/s3/src/data_transport.rs b/crates/s3/src/data_transport.rs index 6f4374fe..3bf39b48 100644 --- a/crates/s3/src/data_transport.rs +++ b/crates/s3/src/data_transport.rs @@ -43,6 +43,11 @@ pub enum RegisteredControlResponse { /// Host-owned HTTPS, credentials, signing, custom headers, and TLS configuration. #[async_trait] pub trait ControlExecutor: Send + Sync { + /// Stable endpoint for sharing provider capability discovery across clients. + fn endpoint(&self) -> Option<&str> { + None + } + /// Read only the status and headers. A declined external GET can return an /// ordinary S3 payload of arbitrary size. async fn execute_headers(&self, request: ControlRequest) -> Result; diff --git a/docs/rdma-build.md b/docs/rdma-build.md index ba34dab9..f77489e2 100644 --- a/docs/rdma-build.md +++ b/docs/rdma-build.md @@ -78,7 +78,11 @@ the process exits. When both windows are unavailable for this reason, waiting operations use a fresh pool within the process registration budget. Retiring a cuObject pool releases its idle registrations. Each quarantined window keeps its own -registration and the pool's budget reservation. +registration and the pool's budget reservation. A native registration also +keeps this reservation if the SDK cannot confirm deregistration. +For the rest of the process, an ordinary HTTP response without an RDMA +receipt disables further probes for the same endpoint, backend and operation +(GET or UploadPart). Concurrent requests share the initial discovery. RustFS can interpret a declined external PUT as an ordinary empty PUT. The client uploads nonempty objects into unpublished multipart parts and diff --git a/nixl/cuobject-client-sys/native/cuobject.cc b/nixl/cuobject-client-sys/native/cuobject.cc index bddb11a2..b031b409 100644 --- a/nixl/cuobject-client-sys/native/cuobject.cc +++ b/nixl/cuobject-client-sys/native/cuobject.cc @@ -1,4 +1,4 @@ -#include "native/cuobject.h" +#include "rustfs-cuobject-client-sys/src/sdk.rs.h" #include #include @@ -29,14 +29,15 @@ static void check(cuObjErr_t status, const char *operation) { } struct NativeWindow::Registration { + rust::Box owner; std::shared_ptr client; std::size_t size; std::uint8_t *data; char *token = nullptr; bool release_failed = false; - Registration(std::shared_ptr owner, std::size_t length) - : client(std::move(owner)), size(length) { + Registration(std::shared_ptr sdk_client, std::size_t length, rust::Box guard) + : owner(std::move(guard)), client(std::move(sdk_client)), size(length) { if (!client) { throw std::invalid_argument("missing cuObject client"); } @@ -61,8 +62,8 @@ struct NativeWindow::Registration { ~Registration() { munmap(data, size); } }; -NativeWindow::NativeWindow(std::shared_ptr client, std::size_t size) - : registration_(std::make_unique(std::move(client), size)) {} +NativeWindow::NativeWindow(std::shared_ptr client, std::size_t size, rust::Box owner) + : registration_(std::make_unique(std::move(client), size, std::move(owner))) {} NativeWindow::~NativeWindow() { auto &r = *registration_; @@ -80,8 +81,8 @@ NativeWindow::~NativeWindow() { registration_.release(); } -std::unique_ptr register_window(std::shared_ptr client, std::size_t size) { - return std::make_unique(std::move(client), size); +std::unique_ptr register_window(std::shared_ptr client, std::size_t size, rust::Box owner) { + return std::make_unique(std::move(client), size, std::move(owner)); } rust::Slice NativeWindow::writable() { diff --git a/nixl/cuobject-client-sys/native/cuobject.h b/nixl/cuobject-client-sys/native/cuobject.h index f89347ff..bb047cfe 100644 --- a/nixl/cuobject-client-sys/native/cuobject.h +++ b/nixl/cuobject-client-sys/native/cuobject.h @@ -7,12 +7,13 @@ namespace rc::cuobject { +struct RegistrationOwner; class Client; std::shared_ptr make_client(); class NativeWindow final { public: - NativeWindow(std::shared_ptr client, std::size_t size); + NativeWindow(std::shared_ptr client, std::size_t size, rust::Box owner); ~NativeWindow(); rust::Slice writable(); void acquire(std::size_t length, bool for_get); @@ -24,6 +25,6 @@ class NativeWindow final { std::unique_ptr registration_; }; -std::unique_ptr register_window(std::shared_ptr client, std::size_t size); +std::unique_ptr register_window(std::shared_ptr client, std::size_t size, rust::Box owner); } // namespace rc::cuobject diff --git a/nixl/cuobject-client-sys/src/lib.rs b/nixl/cuobject-client-sys/src/lib.rs index afa7af8a..3ad76244 100644 --- a/nixl/cuobject-client-sys/src/lib.rs +++ b/nixl/cuobject-client-sys/src/lib.rs @@ -8,6 +8,7 @@ )] mod sdk; +pub use sdk::RegistrationOwner; pub use sdk::ffi::{make_client, register_window}; pub type ClientHandle = cxx::SharedPtr; pub type WindowHandle = cxx::UniquePtr; diff --git a/nixl/cuobject-client-sys/src/sdk.rs b/nixl/cuobject-client-sys/src/sdk.rs index fb943c44..e82300a3 100644 --- a/nixl/cuobject-client-sys/src/sdk.rs +++ b/nixl/cuobject-client-sys/src/sdk.rs @@ -1,7 +1,21 @@ //! Private interface to the NVIDIA client and its registered host windows. +/// Held by the native registration alongside its mapping and SDK client. +pub struct RegistrationOwner { + _owner: std::sync::Arc, +} +impl RegistrationOwner { + pub fn new(owner: std::sync::Arc) -> Box { + Box::new(Self { _owner: owner }) + } +} + #[cxx::bridge(namespace = "rc::cuobject")] pub(super) mod ffi { + extern "Rust" { + type RegistrationOwner; + } + // SAFETY: every mutable view borrows its pinned window. An outstanding // token excludes host access until the SDK confirms its release. unsafe extern "C++" { @@ -13,6 +27,7 @@ pub(super) mod ffi { fn register_window( client: SharedPtr, size: usize, + owner: Box, ) -> Result>; fn writable(self: Pin<&mut NativeWindow>) -> Result<&mut [u8]>; fn acquire(self: Pin<&mut NativeWindow>, length: usize, for_get: bool) -> Result<()>; diff --git a/nixl/cuobject-client/src/lib.rs b/nixl/cuobject-client/src/lib.rs index 825992e5..8da18ee3 100644 --- a/nixl/cuobject-client/src/lib.rs +++ b/nixl/cuobject-client/src/lib.rs @@ -13,9 +13,14 @@ impl Client { sys::make_client().map(Self).map_err(io::Error::other) } - /// Registers a host mapping that keeps its native client alive. - pub fn register(&self, bytes: usize) -> io::Result { - sys::register_window(self.0.clone(), bytes) + /// Keeps the client and its accounting owner alive until the SDK confirms + /// deregistration, including when teardown cannot release the mapping. + pub fn register( + &self, + bytes: usize, + owner: std::sync::Arc, + ) -> io::Result { + sys::register_window(self.0.clone(), bytes, sys::RegistrationOwner::new(owner)) .map(Window) .map_err(io::Error::other) } diff --git a/nixl/src/buffer.rs b/nixl/src/buffer.rs index 120676f9..c7cb1fea 100644 --- a/nixl/src/buffer.rs +++ b/nixl/src/buffer.rs @@ -15,10 +15,15 @@ pub(super) enum Buffer { CuObject(crate::nvidia::HostBuffer), } -pub(super) fn register(backend: RdmaBackend, size: usize, count: usize) -> Result> { +pub(super) fn register( + backend: RdmaBackend, + size: usize, + count: usize, + _budget: &crate::pool::Budget, +) -> Result> { if backend == RdmaBackend::CuObject { #[cfg(feature = "cuobject")] - return crate::nvidia::register(size, count); + return crate::nvidia::register(size, count, _budget); #[cfg(not(feature = "cuobject"))] return Err(Error::UnsupportedFeature( "The cuObject backend is not installed".into(), diff --git a/nixl/src/main.rs b/nixl/src/main.rs index f71db3ea..aa80de3e 100644 --- a/nixl/src/main.rs +++ b/nixl/src/main.rs @@ -11,7 +11,7 @@ mod wire; use rc_core::RdmaBackend; fn register(backend: RdmaBackend) { - let factory = std::sync::Arc::new(transport::Factory(backend)); + let factory = std::sync::Arc::new(transport::Factory::new(backend)); if let Err(error) = rc_s3::data_transport::install_rdma_backend(backend, factory) { eprintln!("{error}"); std::process::exit(error.exit_code()); diff --git a/nixl/src/nvidia.rs b/nixl/src/nvidia.rs index 8ffd039a..e1b8be39 100644 --- a/nixl/src/nvidia.rs +++ b/nixl/src/nvidia.rs @@ -11,11 +11,15 @@ fn sdk_error(error: std::io::Error) -> Error { Error::General(format!("NVIDIA cuObject: {error}")) } -pub(super) fn register(size: usize, count: usize) -> Result> { +pub(super) fn register( + size: usize, + count: usize, + budget: &crate::pool::Budget, +) -> Result> { let client = Client::open().map_err(sdk_error)?; (0..count) .map(|_| { - let raw = client.register(size).map_err(sdk_error)?; + let raw = client.register(size, budget.clone()).map_err(sdk_error)?; Ok(Buffer::CuObject(HostBuffer { raw, #[cfg(test)] diff --git a/nixl/src/pool.rs b/nixl/src/pool.rs index f3bad5bd..cf558526 100644 --- a/nixl/src/pool.rs +++ b/nixl/src/pool.rs @@ -12,7 +12,7 @@ const SMALL_WINDOW: usize = 1024 * 1024; const WINDOWS_PER_POOL: usize = 2; static AGENTS: Semaphore = Semaphore::const_new(8); // Keep the exposed registration and its budget, so the retired pool can free its idle buffers. -type Budget = Arc>; +pub(super) type Budget = Arc>; static QUARANTINE: Mutex> = Mutex::new(Vec::new()); fn window_size(required: u64) -> usize { @@ -75,13 +75,14 @@ impl Pool { let budget = AGENTS .try_acquire() .map_err(|_| Error::General("RDMA registered memory budget exhausted".into()))?; - let buffers = buffer::register(backend, size, WINDOWS_PER_POOL)?; + let budget = Arc::new(budget); + let buffers = buffer::register(backend, size, WINDOWS_PER_POOL, &budget)?; Ok(Arc::new(Self { size, free: Mutex::new(buffers), available: Semaphore::new(WINDOWS_PER_POOL), lost: watch::Sender::new(0), - budget: Arc::new(budget), + budget, })) } diff --git a/nixl/src/transport.rs b/nixl/src/transport.rs index 96697f64..8f258937 100644 --- a/nixl/src/transport.rs +++ b/nixl/src/transport.rs @@ -15,13 +15,106 @@ use crate::pool::{Exposed, Pools, WINDOW, Window}; use crate::wire; use rc_core::RdmaBackend; -pub(crate) struct Factory(pub(crate) RdmaBackend); +use std::collections::HashMap; +use std::sync::Mutex; +use std::sync::atomic::{AtomicU8, Ordering}; +use tokio::sync::{Semaphore, SemaphorePermit}; + +pub(crate) struct Factory { + backend: RdmaBackend, + endpoints: Mutex>>, +} + +impl Factory { + pub(crate) fn new(backend: RdmaBackend) -> Self { + Self { + backend, + endpoints: Mutex::default(), + } + } + + fn support(&self, endpoint: Option<&str>) -> Arc { + match endpoint { + Some(endpoint) => self + .endpoints + .lock() + .unwrap_or_else(|e| e.into_inner()) + .entry(endpoint.to_owned()) + .or_default() + .clone(), + None => Arc::default(), + } + } +} + +#[derive(Default)] +struct EndpointSupport { + get: Capability, + upload_part: Capability, +} + +struct Capability { + state: AtomicU8, + probe: Semaphore, +} + +impl Default for Capability { + fn default() -> Self { + Self { + state: AtomicU8::new(Self::UNKNOWN), + probe: Semaphore::new(1), + } + } +} + +impl Capability { + const UNKNOWN: u8 = 0; + const SUPPORTED: u8 = 1; + const HTTP_ONLY: u8 = 2; + + // Only the first operation probes. Once a response identifies the + // transport, ordinary concurrent transfers need no permit. + async fn enter(&self) -> DataTransportResult>> { + let permit = if self.state.load(Ordering::Acquire) == Self::UNKNOWN { + self.probe.acquire().await.ok() + } else { + None + }; + if self.state.load(Ordering::Acquire) == Self::HTTP_ONLY { + return Err(unavailable(Error::UnsupportedFeature( + "Endpoint served this operation over HTTP".into(), + ))); + } + Ok(permit) + } + + fn supported(&self) { + if self + .state + .compare_exchange( + Self::UNKNOWN, + Self::SUPPORTED, + Ordering::AcqRel, + Ordering::Acquire, + ) + .is_ok() + { + self.probe.close(); + } + } + + fn http_only(&self) { + self.state.store(Self::HTTP_ONLY, Ordering::Release); + self.probe.close(); + } +} impl ObjectDataTransportFactory for Factory { fn create(&self, control: Arc) -> Result> { Ok(Arc::new(Transport { + support: self.support(control.endpoint()), control, - pools: Pools::new(self.0), + pools: Pools::new(self.backend), })) } } @@ -29,6 +122,7 @@ impl ObjectDataTransportFactory for Factory { struct Transport { control: Arc, pools: Pools, + support: Arc, } fn failed(state: DataTransferState, source: Error) -> DataTransportError { diff --git a/nixl/src/transport/download.rs b/nixl/src/transport/download.rs index 153d635c..0a378a42 100644 --- a/nixl/src/transport/download.rs +++ b/nixl/src/transport/download.rs @@ -53,6 +53,31 @@ fn read_request( wire::request(method, path, query, headers) } +// The caller may retry over HTTP only if both ranges declined before output. +pub(super) fn merged_ranges( + first: DataTransportResult<()>, + second: DataTransportResult, +) -> DataTransportResult { + match (first, second) { + (Ok(()), Ok(value)) => Ok(value), + (Err(first), Err(second)) => { + if second.state == DataTransferState::OutcomeUnknown + || first.state == DataTransferState::NotAccepted + { + Err(second) + } else { + Err(first) + } + } + (Ok(()), Err(mut error)) | (Err(mut error), Ok(_)) => { + if error.state == DataTransferState::NotAccepted { + error.state = DataTransferState::ConfirmedFailure; + } + Err(error) + } + } +} + impl Transport { async fn fetch( &self, @@ -98,6 +123,7 @@ impl Transport { // An ordinary successful GET returned the object in its HTTP body. // It is safe to try the ordinary reader before publishing any bytes. // A missing receipt permits the S3 fallback but does not prove the window is idle. + self.support.get.http_only(); return Err(unavailable(Error::UnsupportedFeature( "The endpoint served GET over HTTP".into(), ))); @@ -108,6 +134,7 @@ impl Transport { ))); } wire::receipt(expected, &response.headers, len as u64).map_err(rejected)?; + self.support.get.supported(); let mut window = exposed.finished().map_err(rejected)?; if wire::field(&response.headers, "content-length") .map_err(rejected)? @@ -153,6 +180,7 @@ impl Transport { "RDMA does not encrypt SSE-C payloads in transit".into(), ))); } + let _probe = self.support.get.enter().await?; let requested_version = request.options.version_id.as_deref(); let mut headers = HeaderMap::new(); if request.options.checksum_mode { @@ -215,7 +243,7 @@ impl Transport { .fetch(&selection, offset, first as usize, ranged, window) .await .map_err(|mut error| { - if offset != 0 { + if offset != 0 && error.state == DataTransferState::NotAccepted { error.state = DataTransferState::ConfirmedFailure; } error @@ -239,11 +267,7 @@ impl Transport { // Settle both control exchanges even when one fails. Only the ordered // consumer updates the checksum, writes bytes and reports progress. let (first_result, second_result) = tokio::join!(publish_first, fetch_second); - first_result?; - let window = second_result.map_err(|mut error| { - error.state = DataTransferState::ConfirmedFailure; - error - })?; + let window = merged_ranges(first_result, second_result)?; target .write_range(window, next, (length == total).then_some(&mut checksum)) .await diff --git a/nixl/src/transport/tests.rs b/nixl/src/transport/tests.rs index 5a7a02e3..0090eb66 100644 --- a/nixl/src/transport/tests.rs +++ b/nixl/src/transport/tests.rs @@ -36,7 +36,9 @@ async fn download( queries: Mutex::default(), get_version, }); - let transport = Factory(RdmaBackend::Nixl).create(endpoint.clone()).unwrap(); + let transport = Factory::new(RdmaBackend::Nixl) + .create(endpoint.clone()) + .unwrap(); let path = RemotePath::new("test", "bucket", "key"); let options = rc_core::TransferReadOptions { version_id: version_id.map(str::to_owned), @@ -98,7 +100,7 @@ async fn a_delete_marker_keeps_its_version_and_exit_code() { } } - let transport = Factory(RdmaBackend::Nixl) + let transport = Factory::new(RdmaBackend::Nixl) .create(Arc::new(DeleteMarker)) .unwrap(); let path = RemotePath::new("test", "bucket", "key"); @@ -169,7 +171,9 @@ async fn only_proven_conditional_rejections_reuse_the_registered_window() { } } let peer = Arc::new(Peer(Mutex::default())); - let transport = Factory(RdmaBackend::Nixl).create(peer.clone()).unwrap(); + let transport = Factory::new(RdmaBackend::Nixl) + .create(peer.clone()) + .unwrap(); let path = RemotePath::new("test", "bucket", "key"); let opts = rc_core::TransferReadOptions::default(); for i in 1..=20 { @@ -212,6 +216,7 @@ async fn rustfs_declines_a_stale_conditional_get_before_dma() { let transport = Transport { control: Arc::new(client), pools: Pools::new(RdmaBackend::CuObject), + support: Arc::default(), }; for _ in 0..20 { let mut headers = HeaderMap::new(); @@ -293,7 +298,7 @@ async fn large_get_submits_both_ranges_and_publishes_in_order() { } for wrong_checksum in [false, true] { - let transport = Factory(RdmaBackend::Nixl) + let transport = Factory::new(RdmaBackend::Nixl) .create(Arc::new(Ranges { second: tokio::sync::Notify::new(), wrong_checksum, @@ -323,3 +328,173 @@ async fn large_get_submits_both_ranges_and_publishes_in_order() { assert_eq!(progress, [WINDOW as u64, total]); } } + +#[tokio::test] +async fn one_declined_range_cannot_hide_an_unconfirmed_sibling() { + use std::sync::atomic::{AtomicUsize, Ordering}; + struct Endpoint(AtomicUsize); + #[async_trait] + impl ControlExecutor for Endpoint { + async fn execute_headers(&self, request: ControlRequest) -> Result { + let mut headers = HeaderMap::new(); + if request.method == Method::HEAD { + headers.insert("etag", HeaderValue::from_static("\"stable\"")); + headers.insert("content-length", HeaderValue::from(WINDOW + 1)); + return Ok(ControlResponse { + status: StatusCode::OK, + headers, + }); + } + self.0.fetch_add(1, Ordering::Relaxed); + if request.headers["range"] + .to_str() + .unwrap() + .starts_with("bytes=0-") + { + Ok(ControlResponse { + status: StatusCode::PARTIAL_CONTENT, + headers, + }) + } else { + Err(Error::Network("control response unavailable".into())) + } + } + } + let endpoint = Arc::new(Endpoint(AtomicUsize::new(0))); + let transport = Factory::new(RdmaBackend::Nixl) + .create(endpoint.clone()) + .unwrap(); + let result = transport + .download( + DownloadRequest { + path: &RemotePath::new("local", "bucket", "key"), + options: &Default::default(), + max_bytes: None, + max_receive_bytes: WINDOW as u64 + 1, + on_progress: &mut |_, _| {}, + }, + &mut tokio::io::sink(), + ) + .await; + assert_eq!(endpoint.0.load(Ordering::Relaxed), 2); + assert_eq!( + result.err().unwrap().state, + DataTransferState::OutcomeUnknown + ); +} + +#[tokio::test] +async fn ordinary_s3_is_probed_once_per_endpoint_backend_and_operation() { + use std::sync::atomic::{AtomicUsize, Ordering}; + struct HttpOnly(AtomicUsize); + #[async_trait] + impl ControlExecutor for HttpOnly { + fn endpoint(&self) -> Option<&str> { + Some("https://ordinary.example") + } + async fn execute_headers(&self, request: ControlRequest) -> Result { + let mut headers = HeaderMap::new(); + if request.method == Method::HEAD { + headers.insert("etag", HeaderValue::from_static("\"tag\"")); + headers.insert("content-length", HeaderValue::from_static("0")); + } else { + self.0.fetch_add(1, Ordering::Relaxed); + } + Ok(ControlResponse { + status: StatusCode::OK, + headers, + }) + } + } + let factory = Factory::new(RdmaBackend::Nixl); + let endpoint = Arc::new(HttpOnly(AtomicUsize::new(0))); + let mut readers = tokio::task::JoinSet::new(); + for _ in 0..20 { + let transport = factory.create(endpoint.clone()).unwrap(); + readers.spawn(async move { + let path = RemotePath::new("lab", "bucket", "key"); + let result = transport + .download( + DownloadRequest { + path: &path, + options: &Default::default(), + max_bytes: None, + max_receive_bytes: 1, + on_progress: &mut |_, _| {}, + }, + &mut tokio::io::sink(), + ) + .await; + assert_eq!( + result.err().expect("ordinary S3 declined RDMA").state, + DataTransferState::NotAccepted + ); + }); + } + while let Some(task) = readers.join_next().await { + task.unwrap(); + } + assert_eq!(endpoint.0.load(Ordering::Relaxed), 1); + let transport = factory.create(endpoint.clone()).unwrap(); + let staged = transport.staged_upload().unwrap(); + let path = RemotePath::new("lab", "bucket", "key"); + assert!(!staged.probe(&path, "upload", 1).await.unwrap()); + assert_eq!( + staged.probe(&path, "upload", 1).await.unwrap_err().state, + DataTransferState::NotAccepted + ); + assert_eq!(endpoint.0.load(Ordering::Relaxed), 2); + for fresh in [ + factory.support(Some("https://other.example")), + Factory::new(RdmaBackend::CuObject).support(endpoint.endpoint()), + ] { + assert!(fresh.get.enter().await.unwrap().is_some()); + } +} + +#[test] +fn range_failure_precedence_preserves_uncertainty_and_output_state() { + use DataTransferState::{ConfirmedFailure, NotAccepted, OutcomeUnknown}; + let cases = [ + (Some(NotAccepted), Some(NotAccepted), NotAccepted), + (Some(NotAccepted), Some(ConfirmedFailure), ConfirmedFailure), + (Some(ConfirmedFailure), Some(NotAccepted), ConfirmedFailure), + (Some(OutcomeUnknown), Some(ConfirmedFailure), OutcomeUnknown), + (Some(ConfirmedFailure), Some(OutcomeUnknown), OutcomeUnknown), + (Some(OutcomeUnknown), None, OutcomeUnknown), + (None, Some(OutcomeUnknown), OutcomeUnknown), + (None, Some(NotAccepted), ConfirmedFailure), + (Some(NotAccepted), None, ConfirmedFailure), + ]; + for (a, b, state) in cases { + let outcome = |s: Option| match s { + Some(s) => Err(failed(s, Error::General("range failure".into()))), + None => Ok(()), + }; + assert_eq!( + download::merged_ranges(outcome(a), outcome(b)) + .unwrap_err() + .state, + state + ); + } +} + +#[cfg(feature = "cuobject")] +#[test] +#[ignore = "requires the NVIDIA cuObject SDK and an RDMA device"] +fn registration_budget_follows_normal_and_retained_native_mappings() { + use rustfs_cuobject_client::{Client, Operation}; + let client = Client::open().unwrap(); + let owner = Arc::new(()); + let available = Arc::downgrade(&owner); + let window = client.register(1 << 20, owner.clone()).unwrap(); + assert!(client.register(0, owner.clone()).is_err()); + drop(window); + assert_eq!(available.strong_count(), 1); + let mut exposed = client.register(1 << 20, owner.clone()).unwrap(); + exposed.acquire_token(Operation::Get, 1).unwrap(); + drop(exposed); + drop(owner); + assert_eq!(available.strong_count(), 1); +} diff --git a/nixl/src/transport/upload.rs b/nixl/src/transport/upload.rs index f0af725f..99fa7f56 100644 --- a/nixl/src/transport/upload.rs +++ b/nixl/src/transport/upload.rs @@ -7,6 +7,7 @@ impl Transport { source: &mut (dyn AsyncRead + Unpin + Send), ) -> DataTransportResult { let len = part_len(&request)?; + let _probe = self.support.upload_part.enter().await?; let mut window = self .pools .reserve(request.content_length) @@ -64,6 +65,7 @@ impl StagedUploadTransport for Transport { upload_id: &str, first_part_bytes: u64, ) -> DataTransportResult { + let _probe = self.support.upload_part.enter().await?; let mut window = self .pools .reserve(first_part_bytes) @@ -92,6 +94,7 @@ impl StagedUploadTransport for Transport { ) -> DataTransportResult { use std::os::unix::fs::FileExt; let len = part_len(&request)?; + let _probe = self.support.upload_part.enter().await?; let mut window = self .pools .reserve(request.content_length) @@ -146,9 +149,11 @@ impl Transport { } if !response.headers.contains_key(RDMA_REPLY_HEADER) { // A missing receipt permits the S3 fallback but does not prove the window is idle. + self.support.upload_part.http_only(); return Ok(None); } wire::receipt(StatusCode::OK, &response.headers, len as u64).map_err(unknown)?; + self.support.upload_part.supported(); drop(exposed.finished().map_err(rejected)?); let etag = wire::field(&response.headers, "etag") .map_err(rejected)? From 760aacc51a908d2565097fcc2b2f899937df5b7d Mon Sep 17 00:00:00 2001 From: GatewayJ <835269233@qq.com> Date: Sun, 22 Nov 2026 12:40:13 +0800 Subject: [PATCH 12/13] test(cuobject): retain accounting after an SDK deregistration error --- docs/rdma-build.md | 12 ++++++++++++ .../tests/failed_deregistration.cc | 6 ++++++ nixl/cuobject-client/tests/registration_budget.rs | 15 +++++++++++++++ 3 files changed, 33 insertions(+) create mode 100644 nixl/cuobject-client/tests/failed_deregistration.cc create mode 100644 nixl/cuobject-client/tests/registration_budget.rs diff --git a/docs/rdma-build.md b/docs/rdma-build.md index f77489e2..0f161b84 100644 --- a/docs/rdma-build.md +++ b/docs/rdma-build.md @@ -110,3 +110,15 @@ test with the same SDK and device configuration used by the CLI: cargo test --locked --manifest-path nixl/Cargo.toml --features cuobject \ cuobject_token_survives_cancellation_and_timeout -- --ignored ``` + +### Test failed cuObject deregistration + +On a Linux RDMA host with the client SDK installed, build the test-only SDK +override and run the registration lifetime test in its own process. + +```sh +c++ -std=c++17 -fPIC -shared -I"$CUOBJCLIENT_ROOT/include" -I"$CUDA_HOME/include" \ + nixl/cuobject-client/tests/failed_deregistration.cc -o /tmp/rc-test-failed-deregistration.so +LD_PRELOAD=/tmp/rc-test-failed-deregistration.so cargo test --manifest-path nixl/Cargo.toml \ + -p rustfs-cuobject-client --features client --test registration_budget -- --ignored +``` diff --git a/nixl/cuobject-client/tests/failed_deregistration.cc b/nixl/cuobject-client/tests/failed_deregistration.cc new file mode 100644 index 00000000..85b768a5 --- /dev/null +++ b/nixl/cuobject-client/tests/failed_deregistration.cc @@ -0,0 +1,6 @@ +// Test-only replacement for the SDK's deregistration operation. +#include + +cuObjErr_t cuObjClient::cuMemObjPutDescriptor(void *) { + return CU_OBJ_INVALID_VALUE; +} diff --git a/nixl/cuobject-client/tests/registration_budget.rs b/nixl/cuobject-client/tests/registration_budget.rs new file mode 100644 index 00000000..986ce3ff --- /dev/null +++ b/nixl/cuobject-client/tests/registration_budget.rs @@ -0,0 +1,15 @@ +#![cfg(feature = "client")] + +use rustfs_cuobject_client::Client; +use std::sync::Arc; + +#[test] +#[ignore = "requires an RDMA device and the failed_deregistration.cc test library in LD_PRELOAD"] +fn failed_descriptor_release_keeps_the_accounting_owner() { + let client = Client::open().unwrap(); + let budget = Arc::new(()); + let retained = Arc::downgrade(&budget); + let window = client.register(1 << 20, budget).unwrap(); + drop(window); + assert_eq!(retained.strong_count(), 1); +} From 7d1a31aa5ce47ec35bbc8b25b0f0615a633d2cc2 Mon Sep 17 00:00:00 2001 From: GatewayJ <835269233@qq.com> Date: Sun, 22 Nov 2026 15:18:01 +0800 Subject: [PATCH 13/13] test(rdma): verify ordered range GET payloads through a NIXL peer --- nixl/src/transport/tests.rs | 71 ++++++++++++++++++++++++++++++------- 1 file changed, 58 insertions(+), 13 deletions(-) diff --git a/nixl/src/transport/tests.rs b/nixl/src/transport/tests.rs index 0090eb66..9b42f5b9 100644 --- a/nixl/src/transport/tests.rs +++ b/nixl/src/transport/tests.rs @@ -238,15 +238,22 @@ async fn rustfs_declines_a_stale_conditional_get_before_dma() { #[tokio::test] async fn large_get_submits_both_ranges_and_publishes_in_order() { + use rustfs_nixl::{ + NIXL_AGENT_HEADER, NIXL_BUFFER_HEADER, NIXL_METADATA_HEADER, NixlConfig, NixlServer, + RdmaToken, + }; + struct Ranges { - second: tokio::sync::Notify, + peer: Arc, + payload: Vec, + second_written: tokio::sync::Notify, wrong_checksum: bool, } #[async_trait] impl ControlExecutor for Ranges { async fn execute_headers(&self, request: ControlRequest) -> Result { - let total = WINDOW + 19; + let total = self.payload.len(); let mut headers = HeaderMap::new(); headers.insert("etag", HeaderValue::from_static("\"immutable\"")); if request.method == Method::HEAD { @@ -273,12 +280,31 @@ async fn large_get_submits_both_ranges_and_publishes_in_order() { let (start, end): (usize, usize) = (start.parse().unwrap(), end.parse().unwrap()); if start == 0 { assert_eq!(end, WINDOW - 1); - tokio::time::timeout(std::time::Duration::from_secs(5), self.second.notified()) - .await - .expect("the second range must enter before the first completes"); + tokio::time::timeout( + std::time::Duration::from_secs(5), + self.second_written.notified(), + ) + .await + .expect("the second range must finish before the first is written"); } else { assert_eq!((start, end), (WINDOW, total - 1)); - self.second.notify_one(); + } + let token = RdmaToken::from_headers( + request.headers[NIXL_AGENT_HEADER].to_str().unwrap(), + Some(request.headers[NIXL_METADATA_HEADER].to_str().unwrap()), + request.headers[NIXL_BUFFER_HEADER].to_str().unwrap(), + ) + .unwrap(); + let mut staging = self.peer.try_reserve().unwrap(); + staging.append(&self.payload[start..=end]).unwrap(); + let (written, _) = self + .peer + .write_to_client_owned("key", &token, 0, staging) + .await + .unwrap(); + assert_eq!(written, (end - start + 1) as u64); + if start == WINDOW { + self.second_written.notify_one(); } headers.insert( "content-range", @@ -288,7 +314,7 @@ async fn large_get_submits_both_ranges_and_publishes_in_order() { headers.insert(RDMA_REPLY_HEADER, HeaderValue::from_static("206")); headers.insert( rustfs_nixl::RDMA_BYTES_TRANSFERRED_HEADER, - HeaderValue::from(end - start + 1), + HeaderValue::from(written), ); Ok(ControlResponse { status: StatusCode::PARTIAL_CONTENT, @@ -297,15 +323,30 @@ async fn large_get_submits_both_ranges_and_publishes_in_order() { } } + let peer = NixlServer::new(&NixlConfig { + agent_name: "rc-ordered-range-peer".into(), + chunk_bytes: WINDOW, + pool_bytes: WINDOW, + ..Default::default() + }) + .unwrap(); for wrong_checksum in [false, true] { + let ranges = Arc::new(Ranges { + peer: peer.clone(), + payload: (0..=250) + .cycle() + .take(WINDOW) + .chain(*b"second range bytes!") + .collect(), + second_written: tokio::sync::Notify::new(), + wrong_checksum, + }); let transport = Factory::new(RdmaBackend::Nixl) - .create(Arc::new(Ranges { - second: tokio::sync::Notify::new(), - wrong_checksum, - })) + .create(ranges.clone()) .unwrap(); let mut progress = Vec::new(); - let total = WINDOW as u64 + 19; + let total = ranges.payload.len() as u64; + let mut output = Vec::with_capacity(ranges.payload.len()); let result = transport .download( DownloadRequest { @@ -315,7 +356,7 @@ async fn large_get_submits_both_ranges_and_publishes_in_order() { max_receive_bytes: total, on_progress: &mut |written, _| progress.push(written), }, - &mut tokio::io::sink(), + &mut output, ) .await; if wrong_checksum { @@ -324,6 +365,10 @@ async fn large_get_submits_both_ranges_and_publishes_in_order() { ); } else { assert_eq!(result.unwrap().bytes_transferred, total); + assert!( + output == ranges.payload, + "downloaded bytes differ from the source object" + ); } assert_eq!(progress, [WINDOW as u64, total]); }