From 275f5a20e352187d0bbaf16a7e8fb7d435a92d3d Mon Sep 17 00:00:00 2001 From: Hauser Zhi Date: Wed, 2 Dec 2026 22:05:50 +0800 Subject: [PATCH] perf(lock): transfer quorum grants directly to guards Return granted leases directly and keep only diagnostic data on failure. Centralize rollback and pending-reply ownership in the quorum round and carry one absolute deadline across retries and peer dispatch. Co-Authored-By: heihutu Co-Authored-By: zhi22915 Co-Authored-By: qunjiazhu Signed-off-by: Hauser Zhi --- crates/lock/src/distributed_lock.rs | 660 +++++++++++----------------- 1 file changed, 261 insertions(+), 399 deletions(-) diff --git a/crates/lock/src/distributed_lock.rs b/crates/lock/src/distributed_lock.rs index 34f20d94ec..d1a4850aa9 100644 --- a/crates/lock/src/distributed_lock.rs +++ b/crates/lock/src/distributed_lock.rs @@ -16,7 +16,7 @@ use crate::{ ObjectKey, client::{BatchAcquireOutcome, LockCleanupOutcome, LockClient}, error::{LockError, Result}, - types::{CacheFenceProof, CacheFenceStamp, LockId, LockInfo, LockRequest, LockResponse, LockStatus, LockType}, + types::{CacheFenceProof, CacheFenceStamp, LockId, LockRequest, LockResponse, LockType}, }; use futures::{ future::join_all, @@ -34,7 +34,6 @@ use tokio::sync::Notify; use tokio::task::{JoinHandle, JoinSet}; use tokio::time::Instant; use tracing::{Instrument as _, debug, warn}; -use uuid::Uuid; const EVENT_DISTRIBUTED_LOCK_CLEANUP: &str = "distributed_lock_cleanup"; const EVENT_NAMESPACE_LOCK_ACQUIRE: &str = "namespace_lock_acquire"; @@ -186,14 +185,6 @@ impl BatchLockPeerDiagnostics { } } -/// Generate a new aggregate lock ID for multiple client locks -fn generate_aggregate_lock_id(resource: &ObjectKey) -> LockId { - LockId { - resource: resource.clone(), - uuid: Uuid::new_v4().to_string(), - } -} - fn is_remote_lock_rpc_failure(error: &str) -> bool { has_case_insensitive_prefix(error, REMOTE_LOCK_RPC_FAILED_PREFIX) || has_case_insensitive_prefix(error, REMOTE_LOCK_RPC_TIMED_OUT_PREFIX) @@ -370,30 +361,41 @@ impl HeldLockEntry { /// Own grants and pending replies until normal completion transfers their cleanup. /// Cancelling the caller must not abort a reply that can still carry a grant. -struct LockAcquireRound { +struct LockAcquireRound<'a> { pending: JoinSet, grants: Vec, - clients: Arc<[Arc]>, - fallback_lock_id: LockId, + clients: &'a Arc<[Arc]>, + fallback_lock_id: &'a LockId, } -impl Drop for LockAcquireRound { - fn drop(&mut self) { - if !self.grants.is_empty() { - DistributedLock::spawn_release_cleanup( - self.grants.iter().map(HeldLockEntry::release_entry).collect(), - "distributed_lock_cancelled_acquisition", - ); - } +impl LockAcquireRound<'_> { + fn release_pending(&mut self, context: &'static str) { if !self.pending.is_empty() { DistributedLock::spawn_pending_cleanup( std::mem::take(&mut self.pending), - self.clients.clone(), - self.fallback_lock_id.clone(), - "distributed_lock_cancelled_acquisition_cleanup", + Arc::clone(self.clients), + (*self.fallback_lock_id).clone(), + context, ); } } + + fn rollback(&mut self, confirmed_context: &'static str, pending_context: &'static str) -> usize { + let grants = std::mem::take(&mut self.grants); + let achieved = grants.len(); + DistributedLock::spawn_release_cleanup( + grants.into_iter().map(|grant| (grant.lock_id, grant.client)).collect(), + confirmed_context, + ); + self.release_pending(pending_context); + achieved + } +} + +impl Drop for LockAcquireRound<'_> { + fn drop(&mut self) { + self.rollback("distributed_lock_cancelled_acquisition", "distributed_lock_cancelled_acquisition_cleanup"); + } } #[derive(Clone, Copy, Default)] @@ -743,10 +745,15 @@ fn normalized_batch_outcome(request: &LockRequest, outcome: Option, - failure_kind: Option, +enum LockAcquireQuorumResult { + Granted(Vec), + Failed(LockAcquireQuorumFailure), +} + +struct LockAcquireQuorumFailure { + error: String, + achieved: usize, + kind: LockAcquireFailureKind, quorum_impossible: bool, attempt_timed_out: bool, } @@ -811,84 +818,56 @@ impl DistributedLock { } let required_quorum = self.required_quorum(request.lock_type); - let LockAcquireQuorumResult { - response: resp, - individual_locks, - failure_kind, - .. - } = self.acquire_lock_quorum_with_retry(request).await?; - if resp.success { - // Use aggregate lock_id from LockResponse's LockInfo - // The aggregate id is what we expose to callers; individual_locks carries - // the real (LockId, client) pairs that must be released. - let aggregate_lock_id = resp - .lock_info - .as_ref() - .map(|info| info.id.clone()) - .unwrap_or_else(|| LockId::new_unique(&request.resource)); - - // Heartbeat operates on the per-client individual locks (their per-client ids), never - // the aggregate id, so refreshes round-trip to the exact backend entries. - let heartbeat = LockHeartbeatConfig { - ttl: request.ttl, - interval: derive_refresh_interval(individual_locks.len(), request.ttl, request.refresh_interval), - refresh_quorum: required_quorum, - owner: request.owner.clone(), - resource: request.resource.clone(), - }; - Ok(Some(DistributedLockGuard::new( - aggregate_lock_id, - individual_locks, - request.lock_type, - heartbeat, - ))) - } else { - // Check if it's a timeout or quorum failure - if let Some(error_msg) = &resp.error { - if request.suppress_contention_logs { - tracing::debug!( - resource = %request.resource, - owner = %request.owner, - "acquire_lock_quorum contention: {}", - error_msg - ); - } else if matches!(failure_kind, Some(LockAcquireFailureKind::NonRetryable)) { + match self.acquire_lock_quorum_with_retry(request).await? { + LockAcquireQuorumResult::Granted(grants) => { + // Refresh and release use the exact IDs returned by the voters. + let heartbeat = LockHeartbeatConfig { + ttl: request.ttl, + interval: derive_refresh_interval(grants.len(), request.ttl, request.refresh_interval), + refresh_quorum: required_quorum, + owner: request.owner.clone(), + resource: request.resource.clone(), + }; + Ok(Some(DistributedLockGuard::new( + LockId::new_unique(&request.resource), + grants, + request.lock_type, + heartbeat, + ))) + } + LockAcquireQuorumResult::Failed(failure) => { + if !request.suppress_contention_logs && matches!(failure.kind, LockAcquireFailureKind::NonRetryable) { warn!( resource = %request.resource, owner = %request.owner, "acquire_lock_quorum error: {}", - error_msg + failure.error ); - } else if matches!( - failure_kind, - Some(LockAcquireFailureKind::RetryableContention | LockAcquireFailureKind::AnchorContention) - ) { - debug!( - resource = %request.resource, - owner = %request.owner, - "acquire_lock_quorum contention: {}", - error_msg - ); - } else { + } else if !request.suppress_contention_logs && matches!(failure.kind, LockAcquireFailureKind::UnrecoverableQuorum) + { debug!( resource = %request.resource, owner = %request.owner, "acquire_lock_quorum final failure: {}", - error_msg + failure.error + ); + } else { + debug!( + resource = %request.resource, + owner = %request.owner, + "acquire_lock_quorum contention: {}", + failure.error ); } - if matches!(failure_kind, Some(LockAcquireFailureKind::UnrecoverableQuorum)) { - let achieved = individual_locks.len(); + if matches!(failure.kind, LockAcquireFailureKind::UnrecoverableQuorum) { Err(LockError::QuorumNotReached { required: required_quorum, - achieved, + achieved: failure.achieved, }) } else { Ok(None) } - } else { - Ok(None) } } } @@ -1814,11 +1793,7 @@ impl DistributedLock { while let Some(join_result) = pending.join_next().await { match join_result { Ok((idx, Ok(resp))) if resp.success => { - let lock_id = resp - .lock_info - .as_ref() - .map(|info| info.id.clone()) - .unwrap_or_else(|| fallback_lock_id.clone()); + let lock_id = resp.lock_info.map(|info| info.id).unwrap_or_else(|| fallback_lock_id.clone()); let Some(client) = clients.get(idx) else { tracing::warn!("{context}: missing client for pending lock cleanup at index {}", idx); continue; @@ -1884,21 +1859,21 @@ impl DistributedLock { } async fn acquire_lock_quorum_with_retry(&self, request: &LockRequest) -> Result { - let start = tokio::time::Instant::now(); + let start = Instant::now(); + let deadline = start.checked_add(request.acquire_timeout).unwrap_or(start); let mut attempt = 1; - let mut last_result: Option = None; + let mut last_failure: Option = None; loop { - let elapsed = start.elapsed(); - if elapsed >= request.acquire_timeout { + let remaining = deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { break; } - let remaining = request.acquire_timeout - elapsed; let mut attempt_request = request.clone(); - // Only retryable contention reaches another round. Give later writer - // attempts enough queue time to outlast readers that entered the gap. - let peer_wait_limit = if request.lock_type == LockType::Exclusive && attempt > 1 { + // Give later writer attempts enough queue time to outlast readers that entered the gap. + let exclusive_retry = request.lock_type == LockType::Exclusive && attempt > 1; + let peer_wait_limit = if exclusive_retry { LOCK_PEER_WRITER_RETRY_TIMEOUT } else { LOCK_PEER_ACQUIRE_TIMEOUT @@ -1906,113 +1881,92 @@ impl DistributedLock { attempt_request.acquire_timeout = self.peer_acquire_timeout(remaining, peer_wait_limit); attempt_request.lock_id = LockId::new_unique(&request.resource); - // 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. - // 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 + // An anchor-only refusal can represent a single stale or contended voter. + let serialize_on_anchor = exclusive_retry + && !last_failure .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?; - if !result.response.success { - tracing::trace!( - target: "rustfs_lock::namespace_owner", - event = EVENT_NAMESPACE_LOCK_ACQUIRE, - component = LOG_COMPONENT_LOCK, - subsystem = LOG_SUBSYSTEM_NAMESPACE, - state = "failed", - namespace = %self.namespace, - resource = %request.resource, - lock_id = %attempt_request.lock_id, - mode = ?request.lock_type, - attempt, - required = self.required_quorum(request.lock_type), - achieved = result.individual_locks.len(), - failure = ?result.failure_kind, - timeout_ms = remaining.as_millis(), - peer_timeout_ms = attempt_request.acquire_timeout.as_millis(), - "Namespace quorum acquisition round failed" - ); - } - if result.response.success - || !matches!( - result.failure_kind, - Some(LockAcquireFailureKind::RetryableContention | LockAcquireFailureKind::AnchorContention) - ) + .is_some_and(|failure| matches!(failure.kind, LockAcquireFailureKind::AnchorContention)); + let failure = match self + .acquire_lock_quorum_once(&attempt_request, deadline, serialize_on_anchor) + .await? { - return Ok(result); + LockAcquireQuorumResult::Granted(grants) => return Ok(LockAcquireQuorumResult::Granted(grants)), + LockAcquireQuorumResult::Failed(failure) => failure, + }; + tracing::trace!( + target: "rustfs_lock::namespace_owner", + event = EVENT_NAMESPACE_LOCK_ACQUIRE, + component = LOG_COMPONENT_LOCK, + subsystem = LOG_SUBSYSTEM_NAMESPACE, + state = "failed", + namespace = %self.namespace, + resource = %request.resource, + lock_id = %attempt_request.lock_id, + mode = ?request.lock_type, + attempt, + required = self.required_quorum(request.lock_type), + achieved = failure.achieved, + failure = ?failure.kind, + timeout_ms = remaining.as_millis(), + peer_timeout_ms = attempt_request.acquire_timeout.as_millis(), + "Namespace quorum acquisition round failed" + ); + if !matches!( + failure.kind, + LockAcquireFailureKind::RetryableContention | LockAcquireFailureKind::AnchorContention + ) { + return Ok(LockAcquireQuorumResult::Failed(failure)); } - // A final retry can time out without establishing whether the - // previously observed quorum failure has recovered. - let remaining = request.acquire_timeout.saturating_sub(start.elapsed()); - let preserve_quorum_failure = result.attempt_timed_out + // A final timeout cannot establish whether an earlier quorum failure recovered. + let remaining = deadline.saturating_duration_since(Instant::now()); + let preserve_quorum_failure = failure.attempt_timed_out && remaining.is_zero() - && last_result.as_ref().is_some_and(|result| result.quorum_impossible); + && last_failure.as_ref().is_some_and(|failure| failure.quorum_impossible); if !preserve_quorum_failure { - last_result = Some(result); + last_failure = Some(failure); } if remaining.is_zero() { break; } let backoff = Self::lock_acquire_retry_backoff(attempt, &mut rand::rng()); - // Keep time for another acquire attempt instead of abandoning the - // caller's remaining budget when the jittered backoff grows large. tokio::time::sleep(backoff.min(remaining / 2)).await; attempt += 1; } - if let Some(mut result) = last_result { - if result.quorum_impossible { - result.failure_kind = Some(LockAcquireFailureKind::UnrecoverableQuorum); - } - Ok(result) - } else { - Ok(LockAcquireQuorumResult { - response: LockResponse::failure("Lock acquisition timeout", request.acquire_timeout), - individual_locks: Vec::new(), - failure_kind: Some(LockAcquireFailureKind::RetryableContention), - quorum_impossible: false, - attempt_timed_out: true, - }) + let mut failure = last_failure.unwrap_or_else(|| Self::lock_acquire_attempt_timeout(0, None, None)); + if failure.quorum_impossible { + failure.kind = LockAcquireFailureKind::UnrecoverableQuorum; } + Ok(LockAcquireQuorumResult::Failed(failure)) } - fn lock_acquire_attempt_timeout_result( - timeout: Duration, - individual_locks: Vec, + fn lock_acquire_attempt_timeout( + achieved: usize, last_failure: Option, last_failure_kind: Option, - ) -> LockAcquireQuorumResult { - let failure_kind = last_failure_kind.unwrap_or(LockAcquireFailureKind::RetryableContention); - + ) -> LockAcquireQuorumFailure { + let kind = last_failure_kind.unwrap_or(LockAcquireFailureKind::RetryableContention); let mut error = "Lock acquisition timeout".to_string(); if let Some(last_failure) = last_failure { error.push_str("; last failure: "); error.push_str(&last_failure); } - - LockAcquireQuorumResult { - response: LockResponse::failure(error, timeout), - individual_locks, - failure_kind: Some(failure_kind), - quorum_impossible: matches!(failure_kind, LockAcquireFailureKind::UnrecoverableQuorum), + LockAcquireQuorumFailure { + error, + achieved, + kind, + quorum_impossible: matches!(kind, LockAcquireFailureKind::UnrecoverableQuorum), attempt_timed_out: true, } } /// Quorum-based lock acquisition: success if at least the required quorum succeeds. - /// Collects all individual lock_ids from successful clients and creates an aggregate lock_id. - /// Returns the LockResponse with aggregate lock_id and individual lock mappings. + /// Transfers the granted leases to the caller once quorum and deadlines are satisfied. async fn acquire_lock_quorum_once( &self, request: &LockRequest, - quorum_timeout: Duration, + quorum_deadline: Instant, serialize_on_anchor: bool, ) -> Result { let voter_count = @@ -2020,13 +1974,16 @@ impl DistributedLock { let required_quorum = self.required_quorum(request.lock_type); let anchor_serialized = serialize_on_anchor && self.clients.len() > 1; let attempt_started = Instant::now(); - let quorum_deadline = attempt_started.checked_add(quorum_timeout).unwrap_or(attempt_started); + let quorum_timeout = quorum_deadline.saturating_duration_since(attempt_started); + if quorum_timeout.is_zero() { + return Ok(LockAcquireQuorumResult::Failed(Self::lock_acquire_attempt_timeout(0, None, None))); + } let grant_valid_until = attempt_started.checked_add(request.ttl).unwrap_or(attempt_started); let mut round = LockAcquireRound { pending: JoinSet::new(), grants: Vec::new(), - clients: self.clients.clone(), - fallback_lock_id: request.lock_id.clone(), + clients: &self.clients, + fallback_lock_id: &request.lock_id, }; let mut next_client_index = 0usize; let initial_target = if anchor_serialized { @@ -2093,26 +2050,8 @@ impl DistributedLock { continue; } }; - let join_result = match next_result { - Some(join_result) => join_result, - None => { - 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 Some(join_result) = next_result else { + break; }; match join_result { @@ -2121,9 +2060,8 @@ impl DistributedLock { let cache_fence_stamp = resp.cache_fence_stamp; let lock_id = resp .lock_info - .as_ref() - .map(|info| info.id.clone()) - .unwrap_or_else(|| round.fallback_lock_id.clone()); + .map(|info| info.id) + .unwrap_or_else(|| (*round.fallback_lock_id).clone()); if let Some(client) = self.clients.get(idx) { round.grants.push(HeldLockEntry { @@ -2144,13 +2082,13 @@ impl DistributedLock { // Before a hedge starts, let the anchor arbitrate contention // without acquiring partial votes at the remaining peers. if anchor_serialized && idx == 0 && next_client_index == 1 { - return Ok(LockAcquireQuorumResult { - response: LockResponse::failure(error, resp.wait_time), - individual_locks: Vec::new(), - failure_kind: Some(LockAcquireFailureKind::AnchorContention), + return Ok(LockAcquireQuorumResult::Failed(LockAcquireQuorumFailure { + error, + achieved: 0, + kind: LockAcquireFailureKind::AnchorContention, quorum_impossible: false, attempt_timed_out: false, - }); + })); } if retries.is_empty() { retries.resize(self.clients.len(), LockVoterRetry::default()); @@ -2189,125 +2127,40 @@ impl DistributedLock { } if self.clients.len().saturating_sub(hard_failures) < required_quorum { - let rollback_count = round.grants.len(); - Self::spawn_release_cleanup( - round.grants.iter().map(HeldLockEntry::release_entry).collect(), - "distributed_lock_quorum_rollback", - ); - if !round.pending.is_empty() { - Self::spawn_pending_cleanup( - std::mem::take(&mut round.pending), - self.clients.clone(), - round.fallback_lock_id.clone(), - "distributed_lock_failure_cleanup", - ); - } - + let achieved = round.rollback("distributed_lock_quorum_rollback", "distributed_lock_failure_cleanup"); let mut error = format!( - "Unrecoverable quorum failure: {rollback_count}/{required_quorum} required; {hard_failures} clients failed" + "Unrecoverable quorum failure: {achieved}/{required_quorum} required; {hard_failures} clients failed" ); if let Some(last_failure) = last_failure { error.push_str("; last failure: "); error.push_str(&last_failure); } - let resp = LockResponse::failure(error, Duration::ZERO); - let failure_kind = last_hard_failure_kind.unwrap_or(LockAcquireFailureKind::UnrecoverableQuorum); - return Ok(LockAcquireQuorumResult { - response: resp, - individual_locks: std::mem::take(&mut round.grants), - failure_kind: Some(failure_kind), + return Ok(LockAcquireQuorumResult::Failed(LockAcquireQuorumFailure { + error, + achieved, + kind: last_hard_failure_kind.unwrap_or(LockAcquireFailureKind::UnrecoverableQuorum), quorum_impossible: true, attempt_timed_out: false, - }); + })); } if round.grants.len() >= required_quorum { - // Timeout polls its inner join first. A ready last vote must - // not override the acquisition deadline after a delayed poll. - if Instant::now() >= quorum_deadline { - 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 now = Instant::now(); + if now >= quorum_deadline { + break; } - // Slow delivery must not turn grants whose conservative lease - // deadline already passed into a successful quorum. - if Instant::now() >= grant_valid_until { - Self::spawn_release_cleanup( - round.grants.iter().map(HeldLockEntry::release_entry).collect(), - "distributed_lock_expired_quorum", - ); - if !round.pending.is_empty() { - Self::spawn_pending_cleanup( - std::mem::take(&mut round.pending), - self.clients.clone(), - round.fallback_lock_id.clone(), - "distributed_lock_expired_quorum_cleanup", - ); - } - return Ok(LockAcquireQuorumResult { - response: LockResponse::failure( - "Lock acquisition timeout: grant lease expired before quorum", - Duration::ZERO, - ), - individual_locks: std::mem::take(&mut round.grants), - failure_kind: Some(LockAcquireFailureKind::RetryableContention), + if now >= grant_valid_until { + let achieved = round.rollback("distributed_lock_expired_quorum", "distributed_lock_expired_quorum_cleanup"); + return Ok(LockAcquireQuorumResult::Failed(LockAcquireQuorumFailure { + error: "Lock acquisition timeout: grant lease expired before quorum".to_string(), + achieved, + kind: LockAcquireFailureKind::RetryableContention, quorum_impossible: false, attempt_timed_out: false, - }); + })); } - if !round.pending.is_empty() { - Self::spawn_pending_cleanup( - std::mem::take(&mut round.pending), - self.clients.clone(), - round.fallback_lock_id.clone(), - "distributed_lock_success_cleanup", - ); - } - - let aggregate_lock_id = generate_aggregate_lock_id(&request.resource); - tracing::debug!( - "Generated aggregate lock_id {} for {} individual locks on resource {}", - aggregate_lock_id, - round.grants.len(), - request.resource - ); - - let resp = LockResponse::success( - LockInfo { - id: aggregate_lock_id, - resource: request.resource.clone(), - lock_type: request.lock_type, - status: LockStatus::Acquired, - owner: request.owner.clone(), - acquired_at: std::time::SystemTime::now(), - expires_at: std::time::SystemTime::now() + request.ttl, - last_refreshed: std::time::SystemTime::now(), - metadata: request.metadata.clone(), - priority: request.priority, - wait_start_time: None, - }, - Duration::ZERO, - ); - return Ok(LockAcquireQuorumResult { - response: resp, - individual_locks: std::mem::take(&mut round.grants), - failure_kind: None, - quorum_impossible: false, - attempt_timed_out: false, - }); + round.release_pending("distributed_lock_success_cleanup"); + return Ok(LockAcquireQuorumResult::Granted(std::mem::take(&mut round.grants))); } let needed = required_quorum.saturating_sub(round.grants.len()); @@ -2322,66 +2175,59 @@ impl DistributedLock { // Scheduled retries cannot rescue an otherwise impossible round. Roll back // its partial cohort so competing exclusive callers can make progress. if round.grants.len() + round.pending.len() + unstarted_clients < required_quorum { - let rollback_count = round.grants.len(); - Self::spawn_release_cleanup( - round.grants.iter().map(HeldLockEntry::release_entry).collect(), - "distributed_lock_quorum_rollback", - ); - if !round.pending.is_empty() { - Self::spawn_pending_cleanup( - std::mem::take(&mut round.pending), - self.clients.clone(), - round.fallback_lock_id.clone(), - "distributed_lock_failure_cleanup", - ); - } - - let mut error = format!("Failed to acquire quorum: {rollback_count}/{required_quorum} required"); - let (failure_kind, quorum_impossible) = if hard_failures > 0 { + let achieved = round.rollback("distributed_lock_quorum_rollback", "distributed_lock_failure_cleanup"); + let mut error = format!("Failed to acquire quorum: {achieved}/{required_quorum} required"); + let quorum_impossible = hard_failures > 0; + let kind = if quorum_impossible { error = format!( - "Unrecoverable quorum failure: {rollback_count}/{required_quorum} required; {hard_failures} clients failed; {error}" + "Unrecoverable quorum failure: {achieved}/{required_quorum} required; {hard_failures} clients failed; {error}" ); - (last_hard_failure_kind.unwrap_or(LockAcquireFailureKind::UnrecoverableQuorum), true) + last_hard_failure_kind.unwrap_or(LockAcquireFailureKind::UnrecoverableQuorum) } else { - (LockAcquireFailureKind::RetryableContention, false) + LockAcquireFailureKind::RetryableContention }; if let Some(last_failure) = last_failure { error.push_str("; last failure: "); error.push_str(&last_failure); } - let resp = LockResponse::failure(error, Duration::ZERO); - return Ok(LockAcquireQuorumResult { - response: resp, - individual_locks: std::mem::take(&mut round.grants), - failure_kind: Some(failure_kind), + return Ok(LockAcquireQuorumResult::Failed(LockAcquireQuorumFailure { + error, + achieved, + kind, quorum_impossible, attempt_timed_out: false, - }); + })); } } - let rollback_count = round.grants.len(); - Self::spawn_release_cleanup( - round.grants.iter().map(HeldLockEntry::release_entry).collect(), - "distributed_lock_quorum_rollback", - ); - let mut error = format!("Failed to acquire quorum: {rollback_count}/{required_quorum} required"); + if Instant::now() >= quorum_deadline { + let achieved = round.rollback("distributed_lock_attempt_timeout", "distributed_lock_attempt_timeout_cleanup"); + return Ok(LockAcquireQuorumResult::Failed(Self::lock_acquire_attempt_timeout( + achieved, + last_failure, + last_failure_kind, + ))); + } + + let achieved = round.rollback("distributed_lock_quorum_rollback", "distributed_lock_failure_cleanup"); + let mut error = format!("Failed to acquire quorum: {achieved}/{required_quorum} required"); if let Some(last_failure) = &last_failure { error.push_str("; last failure: "); error.push_str(last_failure); } - let resp = LockResponse::failure(error, Duration::ZERO); - Ok(LockAcquireQuorumResult { - response: resp, - individual_locks: std::mem::take(&mut round.grants), - failure_kind: Some(if hard_failures > 0 { - last_hard_failure_kind.unwrap_or(LockAcquireFailureKind::UnrecoverableQuorum) - } else { - last_failure_kind.unwrap_or(LockAcquireFailureKind::RetryableContention) - }), - quorum_impossible: hard_failures > 0, + let quorum_impossible = hard_failures > 0; + let kind = if quorum_impossible { + last_hard_failure_kind.unwrap_or(LockAcquireFailureKind::UnrecoverableQuorum) + } else { + last_failure_kind.unwrap_or(LockAcquireFailureKind::RetryableContention) + }; + Ok(LockAcquireQuorumResult::Failed(LockAcquireQuorumFailure { + error, + achieved, + kind, + quorum_impossible, attempt_timed_out: false, - }) + })) } } @@ -2412,8 +2258,8 @@ mod tests { use super::{ BatchLockPeerDiagnostics, DEFERRED_UNLOCK_BACKOFF, DistributedLock, LOCK_ACQUIRE_RETRY_INITIAL_BACKOFF, LOCK_ACQUIRE_SPARE_HEDGES, LOCK_PEER_ACQUIRE_TIMEOUT, LOCK_PEER_WRITER_RETRY_TIMEOUT, LockAcquireFailureKind, - LockLostSignal, UNLOCK_RETRY_ATTEMPTS, UNLOCK_RETRY_BACKOFF, is_definitive_lock_contention, is_remote_lock_rpc_failure, - should_warn_lock_failure, + LockAcquireQuorumFailure, LockAcquireQuorumResult, LockLostSignal, UNLOCK_RETRY_ATTEMPTS, UNLOCK_RETRY_BACKOFF, + is_definitive_lock_contention, is_remote_lock_rpc_failure, should_warn_lock_failure, }; use crate::{ GlobalLockManager, LocalClient, LockCleanupOutcome, LockError, LockId, LockInfo, LockRequest, LockResponse, LockStats, @@ -2430,6 +2276,13 @@ mod tests { }; use tokio::time::Instant; + fn expect_quorum_failure(result: LockAcquireQuorumResult) -> LockAcquireQuorumFailure { + let LockAcquireQuorumResult::Failed(failure) = result else { + panic!("expected quorum acquisition to fail"); + }; + failure + } + #[derive(Clone, Copy, Debug)] enum RefreshOutcome { Alive, // Ok(true) refresh succeeded @@ -3872,12 +3725,14 @@ mod tests { let started = tokio::time::Instant::now(); let result = lock - .acquire_lock_quorum_once(&request, request.acquire_timeout, true) + .acquire_lock_quorum_once(&request, Instant::now() + 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); + let LockAcquireQuorumResult::Granted(grants) = result else { + panic!("the three remaining voters should form quorum"); + }; + assert_eq!(grants.len(), 3); assert_eq!(started.elapsed(), expected_elapsed); assert_eq!(anchor.requested_acquires.load(Ordering::SeqCst), 1); wait_for_acquisition_cleanup(&[anchor]).await; @@ -3905,7 +3760,7 @@ mod tests { .with_acquire_timeout(Duration::from_secs(2)); let result = lock - .acquire_lock_quorum_once(&request, request.acquire_timeout, true) + .acquire_lock_quorum_once(&request, Instant::now() + request.acquire_timeout, true) .await .expect("the first voter can report definitive contention"); @@ -3914,8 +3769,8 @@ mod tests { .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))); + let failure = expect_quorum_failure(result); + assert_matches!(failure.kind, LockAcquireFailureKind::AnchorContention); } } @@ -3937,11 +3792,11 @@ mod tests { let started = tokio::time::Instant::now(); let result = lock - .acquire_lock_quorum_once(&request, request.acquire_timeout, true) + .acquire_lock_quorum_once(&request, Instant::now() + request.acquire_timeout, true) .await .expect("the silent anchor must leave time for the remaining voters"); - assert!(!result.response.success); + expect_quorum_failure(result); let calls = seen_timeouts.lock().expect("record fallback voter waits"); assert!(calls.len() >= 3); for (_, dispatched, wait) in &calls[..3] { @@ -4288,7 +4143,26 @@ mod tests { } #[tokio::test(start_paused = true)] - async fn acquire_quorum_timeout_preserves_partial_grants() { + async fn expired_caller_deadline_skips_the_next_round() { + let client = Arc::new(SequencedClient::new(Vec::new(), Arc::default())); + let lock = DistributedLock::new("test".to_owned(), vec![client.clone()], 1); + let request = LockRequest::new(ObjectKey::new("bucket", "expired"), LockType::Exclusive, "owner") + .with_acquire_timeout(Duration::from_secs(1)); + let deadline = Instant::now() + request.acquire_timeout; + tokio::time::advance(request.acquire_timeout).await; + + let failure = expect_quorum_failure( + lock.acquire_lock_quorum_once(&request, deadline, false) + .await + .expect("expired round should finish without a peer request"), + ); + assert!(failure.attempt_timed_out); + assert_eq!(failure.achieved, 0); + assert_eq!(client.requested_acquires.load(Ordering::SeqCst), 0); + } + + #[tokio::test(start_paused = true)] + async fn acquire_quorum_timeout_reports_and_releases_partial_grants() { let clients = (0..4) .map(|index| { Arc::new(SequencedClient::new( @@ -4307,14 +4181,13 @@ mod tests { let request = LockRequest::new(ObjectKey::new("bucket", "partial-grants"), LockType::Shared, "owner") .with_acquire_timeout(Duration::from_secs(1)); let result = lock - .acquire_lock_quorum_once(&request, request.acquire_timeout, false) + .acquire_lock_quorum_once(&request, Instant::now() + request.acquire_timeout, false) .await .expect("partial quorum should return a timeout response"); - assert!(!result.response.success); - assert!(result.attempt_timed_out); - assert_matches!(result.failure_kind, Some(LockAcquireFailureKind::RetryableContention)); - assert_eq!(result.individual_locks.len(), 1, "retain received grants for timeout diagnostics"); - assert_eq!(result.individual_locks[0].lock_id, request.lock_id); + let failure = expect_quorum_failure(result); + assert!(failure.attempt_timed_out); + assert_matches!(failure.kind, LockAcquireFailureKind::RetryableContention); + assert_eq!(failure.achieved, 1, "report the confirmed grant in timeout diagnostics"); wait_for_acquisition_cleanup(&clients).await; } @@ -4333,18 +4206,10 @@ mod tests { let request = LockRequest::new(ObjectKey::new("bucket", "object"), LockType::Exclusive, "owner") .with_acquire_timeout(Duration::from_millis(120)); - let result = lock.acquire_lock_quorum_with_retry(&request).await.unwrap(); + let failure = expect_quorum_failure(lock.acquire_lock_quorum_with_retry(&request).await.unwrap()); - assert_matches!(result.failure_kind, Some(LockAcquireFailureKind::NonRetryable)); - assert!( - result - .response - .error - .as_deref() - .is_some_and(|error| error.contains("permission denied")), - "unexpected response: {:?}", - result.response - ); + assert_matches!(failure.kind, LockAcquireFailureKind::NonRetryable); + assert!(failure.error.contains("permission denied"), "unexpected error: {}", failure.error); } #[tokio::test] @@ -4517,11 +4382,11 @@ mod tests { let request = LockRequest::new(ObjectKey::new("bucket", "object"), LockType::Exclusive, "owner") .with_acquire_timeout(Duration::from_secs(2)); let result = lock - .acquire_lock_quorum_once(&request, request.acquire_timeout, false) + .acquire_lock_quorum_once(&request, Instant::now() + request.acquire_timeout, false) .await .expect("round result"); - assert!(!result.response.success); - assert!(result.attempt_timed_out); + let failure = expect_quorum_failure(result); + assert!(failure.attempt_timed_out); assert_eq!(clients[2].requested_acquires.load(Ordering::SeqCst), 1); wait_for_acquisition_cleanup(&clients).await; } @@ -4539,13 +4404,13 @@ mod tests { .with_acquire_timeout(Duration::from_secs(2)); let started = Instant::now(); let result = lock - .acquire_lock_quorum_once(&request, request.acquire_timeout, false) + .acquire_lock_quorum_once(&request, Instant::now() + request.acquire_timeout, false) .await .expect("round result"); - assert!(!result.response.success); - assert!(result.attempt_timed_out); + let failure = expect_quorum_failure(result); + assert!(failure.attempt_timed_out); assert_eq!(started.elapsed(), request.acquire_timeout); - assert_eq!(result.individual_locks.len(), 2, "retries must not duplicate existing votes"); + assert_eq!(failure.achieved, 2, "retries must not duplicate existing votes"); assert_eq!(clients[2].requested_acquires.load(Ordering::SeqCst), 4, "250ms, 500ms, 750ms backoffs"); wait_for_acquisition_cleanup(&clients).await; } @@ -4576,12 +4441,12 @@ mod tests { .with_acquire_timeout(Duration::from_secs(2)); let started = Instant::now(); let result = lock - .acquire_lock_quorum_once(&request, request.acquire_timeout, false) + .acquire_lock_quorum_once(&request, Instant::now() + request.acquire_timeout, false) .await .expect("round result"); - assert!(!result.response.success); + let failure = expect_quorum_failure(result); assert!( - !result.attempt_timed_out, + !failure.attempt_timed_out, "a split minority must yield instead of retaining grants until the deadline" ); assert_eq!(started.elapsed(), Duration::ZERO); @@ -4604,11 +4469,11 @@ mod tests { let request = LockRequest::new(ObjectKey::new("bucket", "object"), LockType::Exclusive, "owner") .with_acquire_timeout(Duration::from_secs(1)); let result = lock - .acquire_lock_quorum_once(&request, request.acquire_timeout, false) + .acquire_lock_quorum_once(&request, Instant::now() + request.acquire_timeout, false) .await .expect("round result"); - assert!(!result.response.success); - assert!(result.attempt_timed_out); + let failure = expect_quorum_failure(result); + assert!(failure.attempt_timed_out); assert_eq!(clients[2].requested_acquires.load(Ordering::SeqCst), 2); wait_for_acquisition_cleanup(&clients).await; } @@ -4719,7 +4584,7 @@ mod tests { .with_acquire_timeout(Duration::from_secs(5)); let mut attempt = Box::pin(tokio::task::unconstrained(lock.acquire_lock_quorum_once( &request, - request.acquire_timeout, + Instant::now() + request.acquire_timeout, false, ))); assert!(matches!(poll!(&mut attempt), Poll::Pending)); @@ -4749,11 +4614,8 @@ mod tests { .await .expect("late votes must be queued before the coordinator resumes"); let result = attempt.await.expect("an expired round should return a response"); - assert!( - !result.response.success, - "ready join results must not override the caller's expired budget" - ); - assert!(result.attempt_timed_out); + let failure = expect_quorum_failure(result); + assert!(failure.attempt_timed_out, "ready join results must respect the expired caller budget"); wait_for_acquisition_cleanup(&clients).await; }