fix(lock): order contended writer retries before collecting quorum votes

This commit is contained in:
overtrue
2026-12-01 08:24:05 +08:00
parent b810191bf7
commit 35a340500a
2 changed files with 92 additions and 13 deletions
+56 -13
View File
@@ -2099,7 +2099,8 @@ impl DistributedLock {
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 {
let retrying_writer = attempt > 1 && request.lock_type == LockType::Exclusive;
let peer_wait_limit = if retrying_writer {
LOCK_PEER_WRITER_RETRY_TIMEOUT
} else {
LOCK_PEER_ACQUIRE_TIMEOUT
@@ -2114,7 +2115,7 @@ impl DistributedLock {
// canonical anchor voter (`clients[0]`) before fanning out to remaining
// voters so N-node local-first split-votes do not livelock across rounds
// while preserving 1-RTT initial fanout and 2s reader-outlast queue time.
let serialize_on_anchor = request.lock_type == LockType::Exclusive && attempt > 1;
let serialize_on_anchor = retrying_writer;
let result = self
.acquire_lock_quorum_once_inner(&attempt_request, remaining, serialize_on_anchor)
.await?;
@@ -2228,14 +2229,17 @@ impl DistributedLock {
fallback_lock_id: request.lock_id.clone(),
};
let mut next_client_index = 0usize;
let initial_target = if anchor_serialized {
1
} else {
required_quorum
.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);
let initial_fanout = required_quorum
.saturating_add(LOCK_ACQUIRE_SPARE_HEDGES)
.min(self.clients.len());
// Retrying writers queue at the same first voter before taking partial grants on other voters.
// The remaining voters are contacted on its response or the first hedge, whichever comes first.
self.spawn_lock_requests_until(
&mut round.pending,
request,
&mut next_client_index,
if anchor_serialized { 1 } else { initial_fanout },
);
let mut last_failure = None;
let mut last_failure_kind = None;
let mut last_hard_failure_kind = None;
@@ -2248,7 +2252,12 @@ impl DistributedLock {
// Spread additional hedges across the existing attempt budget; fast
// quorums still use only the initial quorum-plus-spare requests.
let hedge_interval = request.acquire_timeout / voter_count;
let hedge_timer = tokio::time::sleep(hedge_interval);
let first_hedge = if anchor_serialized {
request.acquire_timeout.min(quorum_timeout / 2)
} else {
hedge_interval
};
let hedge_timer = tokio::time::sleep(first_hedge);
tokio::pin!(hedge_timer);
while !round.pending.is_empty() {
@@ -2293,7 +2302,11 @@ impl DistributedLock {
}
_ = &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 target_in_flight = if anchor_serialized && next_client_index == 1 {
initial_fanout
} else {
round.pending.len().saturating_add(1)
};
self.spawn_lock_requests_until(
&mut round.pending, request, &mut next_client_index, target_in_flight,
);
@@ -2635,7 +2648,7 @@ mod batch_retry_tests;
#[cfg(test)]
mod tests {
use super::{
BatchLockPeerDiagnostics, DEFERRED_UNLOCK_BACKOFF, DistributedLock, LOCK_ACQUIRE_RETRY_INITIAL_BACKOFF,
BatchLockPeerDiagnostics, DEFERRED_UNLOCK_BACKOFF, DistributedLock, HeldLockEntry, 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,
@@ -3101,6 +3114,36 @@ mod tests {
drop(guard);
}
#[tokio::test(start_paused = true)]
async fn contended_write_retry_can_form_a_quorum_without_the_first_voter() {
let peers = (0..4)
.map(|index| {
let delay = if index == 0 { Duration::from_secs(30) } else { Duration::ZERO };
Arc::new(SequencedClient::new(
vec![AcquirePlan::Success { delay }],
Arc::new(Mutex::new(Vec::new())),
)) as Arc<dyn LockClient>
})
.collect();
let lock = DistributedLock::new("hot-write-fallback".to_owned(), peers, 3);
let budget = Duration::from_secs(2);
let request =
LockRequest::new(ObjectKey::new("bucket", "hot"), LockType::Exclusive, "writer").with_acquire_timeout(budget);
let started = Instant::now();
let votes = lock
.acquire_lock_quorum_once_inner(&request, budget, true)
.await
.expect("retry round");
assert!(votes.response.success);
assert_eq!(votes.individual_locks.len(), 3);
assert!(started.elapsed() < budget);
DistributedLock::release_entries(
votes.individual_locks.iter().map(HeldLockEntry::release_entry).collect(),
"test_ordered_retry",
)
.await;
}
#[tokio::test(start_paused = true)]
async fn fast_read_quorum_keeps_initial_fanout_bound() {
let peers: Vec<_> = (0..8)
+36
View File
@@ -1071,6 +1071,42 @@ async fn test_namespace_lock_distributed_reclaims_expired_same_resource_after_fa
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn four_ingress_nodes_contending_for_one_hot_write_key() {
let clients = (0..4)
.map(|_| Arc::new(LocalClient::with_manager(Arc::new(GlobalLockManager::new()))) as Arc<dyn LockClient>)
.collect::<Vec<_>>();
let coordinators = (0..4)
.map(|_| Arc::new(NamespaceLock::Distributed(DistributedLock::new("hot-key".to_owned(), clients.clone(), 3))))
.collect::<Vec<_>>();
let ready = Arc::new(tokio::sync::Barrier::new(32));
let active = Arc::new(AtomicUsize::new(0));
let mut writers = tokio::task::JoinSet::new();
for i in 0..32 {
let coordinator = coordinators[i % coordinators.len()].clone();
let ready = ready.clone();
let active = active.clone();
writers.spawn(async move {
ready.wait().await;
let guard = coordinator
.get_write_lock(ObjectKey::new("bucket", "same-key"), &format!("writer-{i}"), Duration::from_secs(5))
.await?;
assert_eq!(active.fetch_add(1, Ordering::SeqCst), 0);
tokio::time::sleep(Duration::from_millis(10)).await;
assert_eq!(active.fetch_sub(1, Ordering::SeqCst), 1);
drop(guard);
Ok::<(), crate::LockError>(())
});
}
let mut completed = 0;
while let Some(result) = writers.join_next().await {
if result.expect("writer task").is_ok() {
completed += 1;
}
}
assert_eq!(completed, 32);
}
#[tokio::test]
async fn four_node_failed_release_converges_without_replica_repair() {
let managers = (0..4).map(|_| Arc::new(GlobalLockManager::new())).collect::<Vec<_>>();