diff --git a/crates/config/src/constants/internode.rs b/crates/config/src/constants/internode.rs index a9687ebe6e..187b871d4f 100644 --- a/crates/config/src/constants/internode.rs +++ b/crates/config/src/constants/internode.rs @@ -71,15 +71,15 @@ const _: () = assert!(DEFAULT_INTERNODE_RPC_TCP_NODELAY); /// unary responses such as `ReadMultiple` and `BatchReadVersion`. Set to 0 to use the /// `tonic`/`hyper` default. Defaults to 1MiB. pub const ENV_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE: &str = "RUSTFS_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE"; -pub const DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE: u32 = 1024 * 1024; +pub const DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE: u32 = 4 * 1024 * 1024; /// HTTP/2 initial connection window size (bytes) for internode gRPC client channels. /// /// Should be >= the stream window so multiple concurrent streams are not starved by the /// connection-level flow-control window. Set to 0 to fall back to the library default. -/// Defaults to 2MiB. +/// Defaults to 16MiB. pub const ENV_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE: &str = "RUSTFS_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE"; -pub const DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE: u32 = 2 * 1024 * 1024; +pub const DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE: u32 = 16 * 1024 * 1024; // Compile-time invariant: the connection-level window must be >= the per-stream window, or // concurrent streams would be starved by the connection-level flow-control budget. @@ -284,23 +284,23 @@ pub const DEFAULT_INTERNODE_IDEMPOTENT_READ_RETRIES: usize = 1; /// Enable control/bulk internode gRPC channel isolation. /// -/// Defaults to `false`: this touches lock-RPC transport routing (consistency-sensitive), so it -/// is opt-in and validated against a baseline before rollout. When `false`, bulk RPCs reuse the -/// control channel exactly as before, so the switch is a single-env rollback. +/// Defaults to `true` so bulk `ReadAll`/`WriteAll`/`ReadMultiple`/`BatchReadVersion` transfers +/// use dedicated bulk HTTP/2 channels instead of head-of-line blocking latency-sensitive +/// `Lock`/`UnLock`/`Refresh`/`DiskInfo` control RPCs under high concurrency. Set +/// `RUSTFS_INTERNODE_CHANNEL_ISOLATION=false` for single-env rollback to legacy shared-channel behavior. pub const ENV_INTERNODE_CHANNEL_ISOLATION: &str = "RUSTFS_INTERNODE_CHANNEL_ISOLATION"; -pub const DEFAULT_INTERNODE_CHANNEL_ISOLATION: bool = false; +pub const DEFAULT_INTERNODE_CHANNEL_ISOLATION: bool = true; -// Compile-time invariant: isolation is opt-in so the default build behaves exactly as before P1. -const _: () = assert!(!DEFAULT_INTERNODE_CHANNEL_ISOLATION); +// Compile-time invariant: channel isolation defaults on so bulk data RPCs cannot starve lock/quorum RPCs. +const _: () = assert!(DEFAULT_INTERNODE_CHANNEL_ISOLATION); /// Number of bulk channels maintained per peer when channel isolation is enabled. /// /// A tonic `Channel` is a single TCP/HTTP2 connection; multiple bulk channels are round-robined -/// to relieve the single-connection throughput ceiling for large transfers. Kept small (default -/// 2) to avoid a connection storm; clamped to at least 1. Set to 1 to isolate bulk onto a single -/// dedicated connection (still separate from control). +/// to relieve the single-connection throughput ceiling for large transfers. Defaults to 4 (matching +/// typical 4-drive-per-node stripes); clamped to at least 1. pub const ENV_INTERNODE_BULK_CHANNELS: &str = "RUSTFS_INTERNODE_BULK_CHANNELS"; -pub const DEFAULT_INTERNODE_BULK_CHANNELS: usize = 2; +pub const DEFAULT_INTERNODE_BULK_CHANNELS: usize = 4; /// Optional receive-window overrides for isolated bulk channels. When unset, inherit the /// corresponding `RUSTFS_INTERNODE_RPC_HTTP2_*` setting. Zero selects the library default. @@ -310,7 +310,7 @@ pub const ENV_INTERNODE_BULK_HTTP2_CONN_WINDOW_SIZE: &str = "RUSTFS_INTERNODE_BU /// Transport admission and pending-buffer limits for isolated bulk channels. These limits /// apply to the tonic service; complete unary bodies are observed separately by RPC metrics. pub const ENV_INTERNODE_BULK_CONCURRENCY_LIMIT: &str = "RUSTFS_INTERNODE_BULK_CONCURRENCY_LIMIT"; -pub const DEFAULT_INTERNODE_BULK_CONCURRENCY_LIMIT: usize = 64; +pub const DEFAULT_INTERNODE_BULK_CONCURRENCY_LIMIT: usize = 128; pub const ENV_INTERNODE_BULK_BUFFER_SIZE: &str = "RUSTFS_INTERNODE_BULK_BUFFER_SIZE"; pub const DEFAULT_INTERNODE_BULK_BUFFER_SIZE: usize = 1024; @@ -501,8 +501,8 @@ mod tests { #[test] fn internode_rpc_channel_tuning_defaults() { - assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE, 1024 * 1024); - assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE, 2 * 1024 * 1024); + assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE, 4 * 1024 * 1024); + assert_eq!(DEFAULT_INTERNODE_RPC_HTTP2_CONN_WINDOW_SIZE, 16 * 1024 * 1024); // The nodelay-on and connection-window >= stream-window invariants are enforced at // compile time next to the constant definitions. } @@ -525,8 +525,8 @@ mod tests { #[test] fn internode_channel_isolation_defaults_and_env_names() { - // The isolation-off default is asserted at compile time next to the constant definition. - assert_eq!(DEFAULT_INTERNODE_BULK_CHANNELS, 2); + // The isolation-on default is asserted at compile time next to the constant definition. + assert_eq!(DEFAULT_INTERNODE_BULK_CHANNELS, 4); assert_eq!(DEFAULT_INTERNODE_BULK_BODY_CONCURRENCY_LIMIT, 0); assert_eq!(DEFAULT_INTERNODE_BULK_BODY_WAIT_TIMEOUT_MS, 1_000); assert_eq!(ENV_INTERNODE_CHANNEL_ISOLATION, "RUSTFS_INTERNODE_CHANNEL_ISOLATION"); diff --git a/crates/config/src/constants/object.rs b/crates/config/src/constants/object.rs index f1b3680a8b..0b427dc673 100644 --- a/crates/config/src/constants/object.rs +++ b/crates/config/src/constants/object.rs @@ -482,7 +482,7 @@ pub const DEFAULT_PUT_MULTIPART_FOREGROUND_ADMISSION_MIN_SIZE_BYTES: usize = 0; /// A short wait smooths transient bursts while still returning S3 /// `SlowDown`/503 before body ingest when the node is already saturated. pub const ENV_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: &str = "RUSTFS_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS"; -pub const DEFAULT_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: u64 = 250; +pub const DEFAULT_PUT_LARGE_FOREGROUND_ADMISSION_WAIT_TIMEOUT_MS: u64 = 2_000; /// Time in milliseconds a multipart UploadPart waits for a foreground write permit. /// diff --git a/crates/ecstore/src/cluster/rpc/remote_locker.rs b/crates/ecstore/src/cluster/rpc/remote_locker.rs index 2fdba588f0..f160f96be4 100644 --- a/crates/ecstore/src/cluster/rpc/remote_locker.rs +++ b/crates/ecstore/src/cluster/rpc/remote_locker.rs @@ -707,7 +707,7 @@ impl RemoteClient { } let next = if health.request_backoff.is_zero() { - (deadline / 2).max(Duration::from_millis(1)) + (deadline / 4).clamp(Duration::from_millis(1), Duration::from_millis(500)) } else { health.request_backoff.saturating_mul(2) }; diff --git a/crates/lock/src/distributed_lock.rs b/crates/lock/src/distributed_lock.rs index ae4f605ada..34f20d94ec 100644 --- a/crates/lock/src/distributed_lock.rs +++ b/crates/lock/src/distributed_lock.rs @@ -67,6 +67,7 @@ const UNRECOVERABLE_QUORUM_FAILURE_PREFIX: &str = "unrecoverable quorum failure" enum LockAcquireFailureKind { NonRetryable, RetryableContention, + AnchorContention, UnrecoverableQuorum, } @@ -395,6 +396,12 @@ impl Drop for LockAcquireRound { } } +#[derive(Clone, Copy, Default)] +struct LockVoterRetry { + deadline: Option, + attempts: u32, +} + /// Keep completed grants and every unconsumed batch reply owned across cancellation. struct LockBatchAcquireRound { pending: JoinSet, @@ -852,7 +859,10 @@ impl DistributedLock { "acquire_lock_quorum error: {}", error_msg ); - } else if matches!(failure_kind, Some(LockAcquireFailureKind::RetryableContention)) { + } else if matches!( + failure_kind, + Some(LockAcquireFailureKind::RetryableContention | LockAcquireFailureKind::AnchorContention) + ) { debug!( resource = %request.resource, owner = %request.owner, @@ -1357,6 +1367,7 @@ impl DistributedLock { request: &LockRequest, next_client_index: &mut usize, target_pending: usize, + quorum_deadline: Instant, ) { while pending.len() < target_pending { if *next_client_index >= self.clients.len() { @@ -1364,18 +1375,29 @@ impl DistributedLock { } let idx = *next_client_index; *next_client_index = (*next_client_index).saturating_add(1); - self.spawn_lock_request(pending, request, idx); + self.spawn_lock_request(pending, request, idx, quorum_deadline); } } - fn spawn_lock_request(&self, pending: &mut JoinSet, request: &LockRequest, idx: usize) { + fn spawn_lock_request( + &self, + pending: &mut JoinSet, + request: &LockRequest, + idx: usize, + quorum_deadline: Instant, + ) { let Some(client) = self.clients.get(idx).cloned() else { return; }; - let request = request.clone(); + let mut request = request.clone(); let scheduled = Instant::now(); pending.spawn(async move { let entered = Instant::now(); + let remaining = quorum_deadline.saturating_duration_since(entered); + if remaining.is_zero() { + return (idx, Err(LockError::timeout(request.resource.to_string(), Duration::ZERO))); + } + request.acquire_timeout = request.acquire_timeout.min(remaining); let response = client.acquire_lock(&request).await; if scheduled.elapsed() >= Duration::from_millis(100) { tracing::trace!( @@ -1887,9 +1909,13 @@ impl DistributedLock { // A peer may grant promptly but deliver its response after its local // contention budget. Keep this round's owners until a response proves // quorum impossible or the caller's remaining budget expires. - // Give the first voter a chance to arbitrate competing writers on retry. - // The normal hedge still covers a silent voter. - let serialize_on_anchor = request.lock_type == LockType::Exclusive && attempt > 1; + // An anchor-only refusal can describe a single stale or contended + // voter. Let the next round try the remaining quorum in parallel. + let serialize_on_anchor = request.lock_type == LockType::Exclusive + && attempt > 1 + && !last_result + .as_ref() + .is_some_and(|result| matches!(result.failure_kind, Some(LockAcquireFailureKind::AnchorContention))); let result = self .acquire_lock_quorum_once(&attempt_request, remaining, serialize_on_anchor) .await?; @@ -1913,7 +1939,12 @@ impl DistributedLock { "Namespace quorum acquisition round failed" ); } - if result.response.success || !matches!(result.failure_kind, Some(LockAcquireFailureKind::RetryableContention)) { + if result.response.success + || !matches!( + result.failure_kind, + Some(LockAcquireFailureKind::RetryableContention | LockAcquireFailureKind::AnchorContention) + ) + { return Ok(result); } @@ -2005,69 +2036,60 @@ impl DistributedLock { .saturating_add(LOCK_ACQUIRE_SPARE_HEDGES) .min(self.clients.len()) }; - self.spawn_lock_requests_until(&mut round.pending, request, &mut next_client_index, initial_target); + self.spawn_lock_requests_until(&mut round.pending, request, &mut next_client_index, initial_target, quorum_deadline); let mut last_failure = None; let mut last_failure_kind = None; let mut last_hard_failure_kind = None; let mut hard_failures = 0usize; - let mut retry_at = vec![None; self.clients.len()]; - let mut contention_retries = vec![0usize; self.clients.len()]; - let start = attempt_started; - // A silent prefix must not hide healthy voters later in the list. - // Spread additional hedges across the existing attempt budget; fast - // quorums still use only the initial quorum-plus-spare requests. + let mut retries: Vec = Vec::new(); let hedge_interval = request.acquire_timeout / voter_count; - let hedge_timer = tokio::time::sleep(hedge_interval); - tokio::pin!(hedge_timer); + // Let the anchor use its peer wait before hedging where the budget allows. + // Keep at least half the round available for a quorum without the anchor. + let first_hedge = if anchor_serialized { + request.acquire_timeout.saturating_add(hedge_interval).min(quorum_timeout / 2) + } else { + hedge_interval + }; + let hedge_timer = tokio::time::sleep_until(attempt_started.checked_add(first_hedge).unwrap_or(quorum_deadline)); + let deadline_timer = tokio::time::sleep_until(quorum_deadline); + tokio::pin!(hedge_timer, deadline_timer); while !round.pending.is_empty() { - let remaining = quorum_timeout.saturating_sub(start.elapsed()); - if remaining.is_zero() { - Self::spawn_release_cleanup( - round.grants.iter().map(HeldLockEntry::release_entry).collect(), - "distributed_lock_attempt_timeout", - ); - Self::spawn_pending_cleanup( - std::mem::take(&mut round.pending), - self.clients.clone(), - round.fallback_lock_id.clone(), - "distributed_lock_attempt_timeout_cleanup", - ); - return Ok(Self::lock_acquire_attempt_timeout_result( - quorum_timeout, - std::mem::take(&mut round.grants), - last_failure, - last_failure_kind, - )); - } - - let next_retry = retry_at.iter().flatten().copied().min(); + let next_retry = retries.iter().filter_map(|retry| retry.deadline).min(); let next_result = tokio::select! { biased; - _ = tokio::time::sleep_until(quorum_deadline) => None, - result = round.pending.join_next(), if !round.pending.is_empty() => result, - _ = tokio::time::sleep_until(next_retry.unwrap_or(quorum_deadline)), if next_retry.is_some() => { + _ = &mut deadline_timer => None, + result = round.pending.join_next() => result, + _ = async { + if let Some(deadline) = next_retry { + tokio::time::sleep_until(deadline).await; + } + }, if next_retry.is_some() => { let now = Instant::now(); if now < quorum_deadline { - for (idx, retry) in retry_at.iter_mut().enumerate() { - if retry.is_some_and(|deadline| deadline <= now) { - *retry = None; - let mut retry_request = request.clone(); - retry_request.acquire_timeout = request.acquire_timeout.min(quorum_deadline - now); - self.spawn_lock_request(&mut round.pending, &retry_request, idx); + for (idx, retry) in retries.iter_mut().enumerate() { + if retry.deadline.is_some_and(|deadline| deadline <= now) { + retry.deadline = None; + self.spawn_lock_request(&mut round.pending, request, idx, quorum_deadline); } } } continue; } _ = &mut hedge_timer, if next_client_index < self.clients.len() => { - if start.elapsed() < quorum_timeout { - let target_in_flight = round.pending.len().saturating_add(1); + let now = Instant::now(); + if now < quorum_deadline { + // A silent anchor should not force one timer interval per voter. + let target_pending = if anchor_serialized && next_client_index == 1 { + required_quorum.saturating_add(LOCK_ACQUIRE_SPARE_HEDGES) + } else { + round.pending.len().saturating_add(1) + }; self.spawn_lock_requests_until( - &mut round.pending, request, &mut next_client_index, target_in_flight, + &mut round.pending, request, &mut next_client_index, target_pending, quorum_deadline, ); } - hedge_timer.set(tokio::time::sleep(hedge_interval)); + hedge_timer.as_mut().reset(now.checked_add(hedge_interval).unwrap_or(quorum_deadline)); continue; } }; @@ -2125,15 +2147,18 @@ impl DistributedLock { return Ok(LockAcquireQuorumResult { response: LockResponse::failure(error, resp.wait_time), individual_locks: Vec::new(), - failure_kind: Some(LockAcquireFailureKind::RetryableContention), + failure_kind: Some(LockAcquireFailureKind::AnchorContention), quorum_impossible: false, attempt_timed_out: false, }); } - contention_retries[idx] = contention_retries[idx].saturating_add(1); - let backoff = LOCK_ACQUIRE_RETRY_INITIAL_BACKOFF - .saturating_mul(contention_retries[idx].try_into().unwrap_or(u32::MAX)); - retry_at[idx] = Instant::now() + if retries.is_empty() { + retries.resize(self.clients.len(), LockVoterRetry::default()); + } + let retry = &mut retries[idx]; + retry.attempts = retry.attempts.saturating_add(1); + let backoff = LOCK_ACQUIRE_RETRY_INITIAL_BACKOFF.saturating_mul(retry.attempts); + retry.deadline = Instant::now() .checked_add(backoff) .filter(|deadline| *deadline < quorum_deadline); } @@ -2291,6 +2316,7 @@ impl DistributedLock { request, &mut next_client_index, needed.saturating_add(LOCK_ACQUIRE_SPARE_HEDGES), + quorum_deadline, ); let unstarted_clients = self.clients.len().saturating_sub(next_client_index); // Scheduled retries cannot rescue an otherwise impossible round. Roll back @@ -3814,19 +3840,65 @@ mod tests { #[tokio::test(start_paused = true)] async fn exclusive_retry_skips_unresponsive_anchor_without_skipping_quorum() { - for error in [ - "Remote lock RPC timed out: peer request breaker is open", - "Remote lock RPC timed out: transport deadline exceeded", + for (plan, expected_elapsed) in [ + ( + AcquirePlan::Failure { + error: "Remote lock RPC timed out: peer request breaker is open", + delay: Duration::ZERO, + }, + Duration::ZERO, + ), + ( + AcquirePlan::Failure { + error: "Remote lock RPC timed out: transport deadline exceeded", + delay: Duration::ZERO, + }, + Duration::ZERO, + ), + ( + AcquirePlan::Success { + delay: Duration::from_secs(3), + }, + Duration::from_secs(1), + ), ] { + let anchor = Arc::new(SequencedClient::new(vec![plan], Arc::default())); + let clients = std::iter::once(anchor.clone() as Arc) + .chain((0..3).map(|_| Arc::new(SequencedClient::new(Vec::new(), Arc::default())) as Arc)) + .collect(); + let lock = DistributedLock::new("test".to_owned(), clients, 3); + let request = LockRequest::new(ObjectKey::new("bucket", "object"), LockType::Exclusive, "owner") + .with_acquire_timeout(Duration::from_secs(2)); + let started = tokio::time::Instant::now(); + + let result = lock + .acquire_lock_quorum_once(&request, request.acquire_timeout, true) + .await + .expect("the three remaining peers can form quorum"); + + assert!(result.response.success, "{:?}", result.response.error); + assert_eq!(result.individual_locks.len(), 3); + assert_eq!(started.elapsed(), expected_elapsed); + assert_eq!(anchor.requested_acquires.load(Ordering::SeqCst), 1); + wait_for_acquisition_cleanup(&[anchor]).await; + } + } + + #[tokio::test(start_paused = true)] + async fn exclusive_retry_avoids_fanout_after_definitive_anchor_contention() { + for delay in [Duration::ZERO, Duration::from_millis(750)] { let anchor = Arc::new(SequencedClient::new( vec![AcquirePlan::Failure { - error, - delay: Duration::ZERO, + error: "Lock acquisition timeout", + delay, }], Arc::default(), )); - let clients = std::iter::once(anchor.clone() as Arc) - .chain((0..3).map(|_| Arc::new(SequencedClient::new(Vec::new(), Arc::default())) as Arc)) + let others: Vec<_> = (0..3) + .map(|_| Arc::new(SequencedClient::new(Vec::new(), Arc::default()))) + .collect(); + let clients = std::iter::once(anchor as Arc) + .chain(others.iter().cloned().map(|client| client as Arc)) .collect(); let lock = DistributedLock::new("test".to_owned(), clients, 3); let request = LockRequest::new(ObjectKey::new("bucket", "object"), LockType::Exclusive, "owner") @@ -3835,36 +3907,83 @@ mod tests { let result = lock .acquire_lock_quorum_once(&request, request.acquire_timeout, true) .await - .expect("the three remaining peers can form quorum"); + .expect("the first voter can report definitive contention"); - assert!(result.response.success, "anchor returned {error}: {:?}", result.response.error); - assert_eq!(result.individual_locks.len(), 3); - assert_eq!(anchor.requested_acquires.load(Ordering::SeqCst), 1); + let fallback_calls: usize = others + .iter() + .map(|client| client.requested_acquires.load(Ordering::SeqCst)) + .sum(); + assert_eq!(fallback_calls, 0, "anchor replied after {delay:?}"); + assert!(!result.response.success); + assert!(matches!(result.failure_kind, Some(LockAcquireFailureKind::AnchorContention))); } } #[tokio::test(start_paused = true)] - async fn exclusive_retry_avoids_fanout_after_definitive_anchor_contention() { + async fn exclusive_retry_hedge_dispatches_the_remaining_quorum_with_the_remaining_budget() { let anchor = Arc::new(SequencedClient::new( - vec![AcquirePlan::Failure { - error: "Lock acquisition timeout", - delay: Duration::ZERO, + vec![AcquirePlan::Success { + delay: Duration::from_secs(3), }], Arc::default(), )); - let other = Arc::new(SequencedClient::new(Vec::new(), Arc::default())); - let lock = DistributedLock::new("test".to_owned(), vec![anchor, other.clone()], 2); + let seen_timeouts = Arc::new(Mutex::new(Vec::new())); + let clients = std::iter::once(anchor as Arc) + .chain((0..3).map(|_| TimeoutRecordingClient::new(seen_timeouts.clone()).into_client())) + .collect(); + let lock = DistributedLock::new("test".to_owned(), clients, 3); let request = LockRequest::new(ObjectKey::new("bucket", "object"), LockType::Exclusive, "owner") .with_acquire_timeout(Duration::from_secs(2)); + let started = tokio::time::Instant::now(); let result = lock .acquire_lock_quorum_once(&request, request.acquire_timeout, true) .await - .expect("the first voter can report definitive contention"); + .expect("the silent anchor must leave time for the remaining voters"); assert!(!result.response.success); - assert!(matches!(result.failure_kind, Some(LockAcquireFailureKind::RetryableContention))); - assert_eq!(other.requested_acquires.load(Ordering::SeqCst), 0); + let calls = seen_timeouts.lock().expect("record fallback voter waits"); + assert!(calls.len() >= 3); + for (_, dispatched, wait) in &calls[..3] { + assert_eq!(dispatched.duration_since(started), request.acquire_timeout / 2); + assert!(*wait <= request.acquire_timeout.saturating_sub(dispatched.duration_since(started))); + } + } + + #[tokio::test(start_paused = true)] + async fn exclusive_retry_can_bypass_an_anchor_with_an_isolated_contender() { + let anchor = Arc::new(SequencedClient::new( + (0..16) + .map(|_| AcquirePlan::Failure { + error: "Lock acquisition timeout", + delay: Duration::ZERO, + }) + .collect(), + Arc::default(), + )); + let clients = std::iter::once(anchor as Arc) + .chain((0..3).map(|_| { + Arc::new(SequencedClient::new( + vec![AcquirePlan::Failure { + error: "Lock acquisition timeout", + delay: Duration::ZERO, + }], + Arc::default(), + )) as Arc + })) + .collect(); + let lock = DistributedLock::new("test".to_owned(), clients, 3); + let request = LockRequest::new(ObjectKey::new("bucket", "object"), LockType::Exclusive, "owner") + .with_acquire_timeout(Duration::from_secs(4)) + .with_refresh_interval(Duration::ZERO); + + let guard = lock + .acquire_guard(&request) + .await + .expect("the other three voters remain available") + .expect("one contended voter must not control all later rounds"); + + assert_eq!(guard.entries.len(), 3); } fn clients_with_initial_quorum_loss(retries: &[AcquirePlan]) -> Vec> { diff --git a/crates/protos/src/channel_reset_tests.rs b/crates/protos/src/channel_reset_tests.rs index 1b6e25c294..67217d8323 100644 --- a/crates/protos/src/channel_reset_tests.rs +++ b/crates/protos/src/channel_reset_tests.rs @@ -102,9 +102,14 @@ async fn accept_peer(listener: TcpListener) -> io::Result { Ok(socket) } -async fn delayed_response_peer(listener: TcpListener, ready: mpsc::Sender<()>, error_resets: Arc) -> io::Result<()> { +async fn delayed_response_peer( + listener: TcpListener, + ready: mpsc::Sender<()>, + error_resets: Arc, + concurrency_limit: usize, +) -> io::Result<()> { let mut socket = accept_peer(listener).await?; - let mut cancelled = Vec::with_capacity(INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT); + let mut cancelled = Vec::with_capacity(concurrency_limit); let mut resets = HashSet::new(); let mut probe = None; loop { @@ -118,9 +123,9 @@ async fn delayed_response_peer(listener: TcpListener, ready: mpsc::Sender<()>, e let credit = u32::try_from(frame.payload.len()).expect("bounded DATA frame").to_be_bytes(); write_frame(&mut socket, WINDOW_UPDATE, 0, 0, &credit).await?; } - HEADERS if cancelled.len() < INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT => { + HEADERS if cancelled.len() < concurrency_limit => { cancelled.push(frame.stream); - if cancelled.len() == INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT { + if cancelled.len() == concurrency_limit { ready.send(()).await.map_err(|_| io::Error::other("test driver stopped"))?; } } @@ -140,7 +145,7 @@ async fn delayed_response_peer(listener: TcpListener, ready: mpsc::Sender<()>, e _ => {} } if let Some(stream) = probe - && resets.len() == INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT + && resets.len() == concurrency_limit { // A raw peer controls bytes already in flight at cancellation. A normal // server would consume RST_STREAM and suppress these delayed responses. @@ -155,12 +160,12 @@ async fn delayed_response_peer(listener: TcpListener, ready: mpsc::Sender<()>, e } } -async fn assert_cancelled_responses_are_ignored(bulk: bool) { +async fn assert_cancelled_responses_are_ignored(bulk: bool, concurrency_limit: usize) { let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind isolated peer"); let address = format!("http://{}", listener.local_addr().expect("peer address")); let (ready_tx, mut ready_rx) = mpsc::channel(1); let error_resets = Arc::new(AtomicUsize::new(0)); - let peer = tokio::spawn(delayed_response_peer(listener, ready_tx, error_resets.clone())); + let peer = tokio::spawn(delayed_response_peer(listener, ready_tx, error_resets.clone(), concurrency_limit)); let cache_key = if bulk { super::bulk_cache_key(&address, 0) } else { @@ -173,7 +178,7 @@ async fn assert_cancelled_responses_are_ignored(bulk: bool) { let mut client = node_service::node_service_client::NodeServiceClient::new(channel); for batch in 0..BATCHES { let mut requests = JoinSet::new(); - for _ in 0..INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT { + for _ in 0..concurrency_limit { let mut pending_client = client.clone(); requests.spawn(async move { pending_client.read_version(node_service::ReadVersionRequest::default()).await }); } @@ -203,14 +208,14 @@ async fn assert_cancelled_responses_are_ignored(bulk: bool) { #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn cancelled_metadata_responses_keep_the_shared_channel_usable() { - assert_cancelled_responses_are_ignored(false).await; + assert_cancelled_responses_are_ignored(false, INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT).await; } #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn cancelled_metadata_responses_keep_the_bulk_channel_usable() { temp_env::async_with_vars( [(rustfs_config::ENV_INTERNODE_BULK_CONCURRENCY_LIMIT, Some("64"))], - assert_cancelled_responses_are_ignored(true), + assert_cancelled_responses_are_ignored(true, 64), ) .await; } diff --git a/crates/protos/src/lib.rs b/crates/protos/src/lib.rs index 1cc951293f..a2fc8616f6 100644 --- a/crates/protos/src/lib.rs +++ b/crates/protos/src/lib.rs @@ -3836,7 +3836,7 @@ fn complete_pending_rebuild_on_cache_hit(dial_addr: &str, cache_key: &str) -> bo } // Limits transport response futures; client RPC metrics separately cover unary body decoding. -pub const INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT: usize = 64; +pub const INTERNODE_CONTROL_RPC_CONCURRENCY_LIMIT: usize = 256; // Quorum reads cancel surplus metadata RPCs in bursts. Keep bounded reset state // for their in-flight replies through the HTTP/2 grace period without spending @@ -5929,7 +5929,7 @@ mod tests { ); assert_eq!( checked_rpc_window(internode_rpc_http2_stream_window()).expect("control setting"), - Some(1024 * 1024) + Some(rustfs_config::DEFAULT_INTERNODE_RPC_HTTP2_STREAM_WINDOW_SIZE) ); }, ) @@ -6024,17 +6024,20 @@ mod tests { #[tokio::test] async fn get_channel_for_class_bulk_reuses_control_cache_when_isolation_disabled() { let _test_guard = TLS02_TEST_LOCK.lock().await; - // Isolation defaults off, so a Bulk request must reuse the control channel keyed by the - // bare address and must NOT create a separate bulk-keyed entry (zero behavior change). - let addr = "http://get-channel-isolation-off-test"; - let channel = Endpoint::from_static("http://127.0.0.1:1").connect_lazy(); - cache_connection(addr.to_string(), channel).await; + temp_env::async_with_vars([(rustfs_config::ENV_INTERNODE_CHANNEL_ISOLATION, Some("false"))], async { + // When isolation is explicitly disabled, a Bulk request must reuse the control channel + // keyed by the bare address and must NOT create a separate bulk-keyed entry. + let addr = "http://get-channel-isolation-off-test"; + let channel = Endpoint::from_static("http://127.0.0.1:1").connect_lazy(); + cache_connection(addr.to_string(), channel).await; - let acquired = get_channel_for_class(addr, ChannelClass::Bulk).await; - assert!(acquired.is_ok()); - assert!(!rustfs_common::has_cached_connection(&bulk_cache_key(addr, 0)).await); + let acquired = get_channel_for_class(addr, ChannelClass::Bulk).await; + assert!(acquired.is_ok()); + assert!(!rustfs_common::has_cached_connection(&bulk_cache_key(addr, 0)).await); - evict_failed_connection_with_log_level(addr, ConnectionEvictionLogLevel::Debug).await; + evict_failed_connection_with_log_level(addr, ConnectionEvictionLogLevel::Debug).await; + }) + .await; } } diff --git a/docs/operations/lock-rpc-storm-protection.md b/docs/operations/lock-rpc-storm-protection.md index 08ac15cbde..a87fa809d1 100644 --- a/docs/operations/lock-rpc-storm-protection.md +++ b/docs/operations/lock-rpc-storm-protection.md @@ -17,7 +17,7 @@ A timed-out request is no longer cancelled. Cancelling sends `RST_STREAM`, and e Three consecutive lock-acquisition timeouts open a request-level per-peer breaker. While open, new `lock` and `lock_batch` calls fail fast as retryable contention; after the backoff window one half-open probe is admitted. The breaker does not block release or refresh traffic, and it is separate from channel eviction. A per-peer in-flight admission limit also bounds requests that were already admitted before the breaker opened. -Single-resource distributed acquisition bounds each peer's contention wait to one second, but keeps pending responses and partial grants in the same quorum round until a response proves that round cannot reach quorum or the caller's remaining acquisition budget expires. A delayed response can still complete a healthy quorum; it does not restart acquisition with a fresh lock ID merely because delivery took longer than the peer's contention wait. Explicit contention failures retain rollback and retry behavior. Grants whose conservative lease deadline has expired before quorum are rolled back. Cancelling acquisition transfers both confirmed grants and pending replies to background cleanup. The caller's total deadline, read/write quorums, and fast quorum return remain unchanged. +In multi-voter single-resource acquisition, the first round caps each peer's contention wait at one second. Exclusive retries allow a longer peer wait and give the first voter time to arbitrate before fanning out. If that voter stays silent, the coordinator contacts enough remaining voters in parallel, reserving at least half the round for fallback. If only the first voter refuses, the next retry uses ordinary parallel quorum so a stale or contended voter cannot block the remaining quorum. Each dispatch caps the peer wait at the remaining round budget. Pending responses and partial grants stay in the same round until a response proves that quorum is impossible or the caller's acquisition budget expires. A delayed response can still complete a healthy quorum; it does not restart acquisition with a fresh lock ID merely because delivery took longer than the peer's contention wait. Explicit contention failures retain rollback and retry behavior. Grants whose conservative lease deadline has expired before quorum are rolled back. Cancelling acquisition transfers both confirmed grants and pending replies to background cleanup. The caller's total deadline, read/write quorums, and fast quorum return remain unchanged. Unlock cleanup that remains unconfirmed after three quick retries continues in the background with a deferred schedule (1s, 2s, 4s, 8s, 16s). Exhausting that schedule means cleanup was not confirmed; it does not prove that the peer still holds the lock. A server-side lease bounds any grant that remains.