diff --git a/crates/lock/src/fast_lock/object_pool.rs b/crates/lock/src/fast_lock/object_pool.rs index 419a0f94d1..50bc419e5c 100644 --- a/crates/lock/src/fast_lock/object_pool.rs +++ b/crates/lock/src/fast_lock/object_pool.rs @@ -95,7 +95,7 @@ impl ObjectLockState { // Reset atomic state self.atomic_state = crate::fast_lock::state::AtomicLockState::new(); - self.publication = std::sync::OnceLock::new(); + self.admission = std::sync::OnceLock::new(); // Clear owners *self.current_owner.write() = None; diff --git a/crates/lock/src/fast_lock/publication.rs b/crates/lock/src/fast_lock/publication.rs index e71f4feeb8..dbf8048753 100644 --- a/crates/lock/src/fast_lock/publication.rs +++ b/crates/lock/src/fast_lock/publication.rs @@ -1,9 +1,9 @@ // Copyright 2026 RustFS Team // SPDX-License-Identifier: Apache-2.0 -//! FIFO admission only for the bucket publication fence. Consecutive readers -//! form a group; a later writer cannot overtake them, nor can later readers -//! overtake a queued writer. This does not limit a current holder's I/O time. +//! FIFO admission for bucket publication fences and contended ordinary writers. +//! Fences enqueue both modes and group consecutive readers. Ordinary objects +//! enqueue only writers, so their existing preference over readers is preserved. use parking_lot::Mutex; use std::{collections::VecDeque, sync::Arc}; @@ -19,19 +19,19 @@ pub(crate) fn applies(key: &ObjectKey) -> bool { } #[derive(Debug, Default)] -pub(super) struct PublicationQueue { +pub(super) struct AdmissionQueue { entries: Mutex, LockMode)>>, pub(super) changed: Notify, } -pub(super) struct PublicationTicket { +pub(super) struct AdmissionTicket { state: Arc, - pub(super) queue: Arc, + pub(super) queue: Arc, token: Arc<()>, mode: LockMode, } -impl PublicationTicket { +impl AdmissionTicket { // Called while the shard map is locked. The waiter counter pins the map // entry until ticket destruction, including cancellation between polls. pub(super) fn new(state: Arc, mode: LockMode) -> Option { @@ -42,10 +42,7 @@ impl PublicationTicket { if !counted { return None; } - let queue = state - .publication - .get_or_init(|| Arc::new(PublicationQueue::default())) - .clone(); + let queue = state.admission.get_or_init(|| Arc::new(AdmissionQueue::default())).clone(); let token = Arc::new(()); queue.entries.lock().push_back((token.clone(), mode)); Some(Self { @@ -80,7 +77,7 @@ impl PublicationTicket { } } -impl Drop for PublicationTicket { +impl Drop for AdmissionTicket { fn drop(&mut self) { { let mut entries = self.queue.entries.lock(); diff --git a/crates/lock/src/fast_lock/shard.rs b/crates/lock/src/fast_lock/shard.rs index 1df6be5828..276c421c3c 100644 --- a/crates/lock/src/fast_lock/shard.rs +++ b/crates/lock/src/fast_lock/shard.rs @@ -21,7 +21,7 @@ use tokio::time::timeout; use crate::fast_lock::{ metrics::ShardMetrics, object_pool::ObjectStatePool, - publication::{self, PublicationTicket}, + publication::{self, AdmissionTicket}, state::ObjectLockState, types::{LockMode, LockResult, ObjectKey, ObjectLockRequest}, }; @@ -85,38 +85,25 @@ pub struct LockShard { active_guards: parking_lot::Mutex>>, } -/// Cancellation-safe waiter counter ticket. -/// -/// Ensures waiting counters are decremented even if the waiting future -/// is cancelled/dropped before the normal post-await path runs. -struct WaiterCounterGuard { - state: Arc, - mode: LockMode, - incremented: bool, +/// Keep a sleeping reader visible until its wait completes or is cancelled. +struct WaitingReader<'a> { + state: &'a ObjectLockState, + counted: bool, } -impl WaiterCounterGuard { - fn new(state: Arc, mode: LockMode) -> Self { - let incremented = match mode { - LockMode::Shared => state.atomic_state.inc_readers_waiting(), - LockMode::Exclusive => state.atomic_state.inc_writers_waiting(), - }; +impl<'a> WaitingReader<'a> { + fn new(state: &'a ObjectLockState) -> Self { Self { state, - mode, - incremented, + counted: state.atomic_state.inc_readers_waiting(), } } } -impl Drop for WaiterCounterGuard { +impl Drop for WaitingReader<'_> { fn drop(&mut self) { - if !self.incremented { - return; - } - match self.mode { - LockMode::Shared => self.state.atomic_state.dec_readers_waiting(), - LockMode::Exclusive => self.state.atomic_state.dec_writers_waiting(), + if self.counted { + self.state.atomic_state.dec_readers_waiting(); } } } @@ -135,7 +122,7 @@ impl LockShard { /// Acquire lock with fast path optimization pub async fn acquire_lock(&self, request: &ObjectLockRequest) -> Result<(), LockResult> { if publication::applies(&request.key) { - return self.acquire_publication(request, Instant::now()).await; + return self.acquire_queued(request, Instant::now(), request.acquire_timeout).await; } // Try fast path first without sampling Instant::now() @@ -144,21 +131,31 @@ impl LockShard { return Ok(()); } - // Slow path with waiting - self.acquire_lock_slow_path(request, Instant::now()).await + let started = Instant::now(); + let budget = self.calculate_adaptive_timeout(request); + match request.mode { + LockMode::Exclusive => self.acquire_queued(request, started, budget).await, + LockMode::Shared => self.acquire_read_slow_path(request, started, budget).await, + } } - fn publication_ticket(&self, request: &ObjectLockRequest) -> Option { + fn admission_ticket(&self, request: &ObjectLockRequest) -> Option { let mut objects = self.objects.write(); let state = objects .entry(request.key.clone()) .or_insert_with(|| Arc::new(*self.object_pool.acquire())) .clone(); - PublicationTicket::new(state, request.mode) + // Pin the entry against cleanup until the ticket owns its waiter count. + let objects = parking_lot::RwLockWriteGuard::downgrade(objects); + #[cfg(test)] + test_pause(TestPausePoint::SlowLookup, &request.key); + let ticket = AdmissionTicket::new(state, request.mode); + drop(objects); + ticket } - async fn acquire_publication(&self, request: &ObjectLockRequest, started: Instant) -> Result<(), LockResult> { - let Some(ticket) = self.publication_ticket(request) else { + async fn acquire_queued(&self, request: &ObjectLockRequest, started: Instant, budget: Duration) -> Result<(), LockResult> { + let Some(ticket) = self.admission_ticket(request) else { return Err(LockResult::Timeout); }; let mut first_attempt = true; @@ -166,7 +163,7 @@ impl LockShard { // Register before checking so a release/cancellation cannot be lost // between the eligibility check and the notification wait. let notified = ticket.queue.changed.notified(); - let remaining = request.acquire_timeout.saturating_sub(started.elapsed()); + let remaining = budget.saturating_sub(started.elapsed()); if !first_attempt && remaining.is_zero() { self.metrics.record_timeout(); return Err(LockResult::Timeout); @@ -189,7 +186,7 @@ impl LockShard { // Batch acquisition must join the same queue, even for a no-wait // attempt. Dropping a failed ticket does not consume a queue turn. return self - .publication_ticket(request) + .admission_ticket(request) .is_some_and(|ticket| ticket.try_acquire(request)); } // Early check to avoid unnecessary lock contention @@ -223,7 +220,7 @@ impl LockShard { // Try atomic acquisition let success = match request.mode { LockMode::Shared => state.try_acquire_shared_fast(&request.owner, request.lock_timeout), - LockMode::Exclusive => state.try_acquire_exclusive_fast(&request.owner, request.lock_timeout), + LockMode::Exclusive => state.try_acquire_unqueued_exclusive(&request.owner, request.lock_timeout), }; drop(objects); @@ -248,7 +245,7 @@ impl LockShard { #[cfg(test)] test_pause(TestPausePoint::FastWriteExisting, &request.key); - let acquired = state.try_acquire_exclusive_fast(&request.owner, request.lock_timeout); + let acquired = state.try_acquire_unqueued_exclusive(&request.owner, request.lock_timeout); drop(objects); if acquired { return Some(state); @@ -257,7 +254,7 @@ impl LockShard { // Create new state from pool and acquire immediately let state_box = self.object_pool.acquire(); let state = Arc::new(*state_box); - if state.try_acquire_exclusive_fast(&request.owner, request.lock_timeout) { + if state.try_acquire_unqueued_exclusive(&request.owner, request.lock_timeout) { objects.insert(request.key.clone(), state.clone()); return Some(state); } @@ -267,11 +264,14 @@ impl LockShard { None } - /// Slow path with async waiting - async fn acquire_lock_slow_path(&self, request: &ObjectLockRequest, start_time: Instant) -> Result<(), LockResult> { - // Use adaptive timeout based on current load and request priority - let adaptive_timeout = self.calculate_adaptive_timeout(request); - let deadline = start_time + adaptive_timeout; + /// Ordinary readers retain writer preference and the pooled notification path. + async fn acquire_read_slow_path( + &self, + request: &ObjectLockRequest, + started: Instant, + budget: Duration, + ) -> Result<(), LockResult> { + let deadline = started + budget; let mut retry_count = 0u32; const MAX_RETRIES: u32 = 10; @@ -302,10 +302,7 @@ impl LockShard { #[cfg(test)] test_pause(TestPausePoint::SlowLookup, &request.key); - let success = match request.mode { - LockMode::Shared => state.try_acquire_shared_fast(&request.owner, request.lock_timeout), - LockMode::Exclusive => state.try_acquire_exclusive_fast(&request.owner, request.lock_timeout), - }; + let success = state.try_acquire_shared_fast(&request.owner, request.lock_timeout); drop(objects); (state, success) }; @@ -325,30 +322,14 @@ impl LockShard { let remaining = deadline - Instant::now(); if retry_count < MAX_RETRIES && remaining > Duration::from_millis(10) { - // For early retries, wait for a release notification bounded by - // an exponential backoff. The bound (not a bare sleep) matters: - // a plain `sleep` subscribes to nothing, so a release during - // the backoff wakes nobody — `notify_writer`/`notify_readers` - // are gated on the waiter counters, which a sleeper never - // increments. Under N-writer same-key contention the lock sits - // free while every loser sleeps out its full backoff, and the - // ladder compounds superlinearly with N. The backoff cap still - // protects against lost/stolen wakeups, exactly as - // NOTIFY_WAIT_CAP does for the post-retry wait below. + // Wait for a release during early backoff, with a cap in case + // another key consumes the pooled notification. let backoff_ms = std::cmp::min(10 << retry_count, 100); // 10ms, 20ms, 40ms, 80ms, 100ms max let backoff_duration = Duration::from_millis(backoff_ms); if backoff_duration < remaining { - match request.mode { - LockMode::Shared => { - let _waiter_guard = WaiterCounterGuard::new(state.clone(), LockMode::Shared); - let _ = timeout(backoff_duration, state.optimized_notify.wait_for_read()).await; - } - LockMode::Exclusive => { - let _waiter_guard = WaiterCounterGuard::new(state.clone(), LockMode::Exclusive); - let _ = timeout(backoff_duration, state.optimized_notify.wait_for_write()).await; - } - } + let _reader = WaitingReader::new(&state); + let _ = timeout(backoff_duration, state.optimized_notify.wait_for_read()).await; retry_count += 1; continue; } @@ -358,21 +339,9 @@ impl LockShard { // notification wait, but bounded by NOTIFY_WAIT_CAP so a lost/stolen // wakeup cannot strand this waiter until the deadline. let wait = remaining.min(NOTIFY_WAIT_CAP); - let wait_result = match request.mode { - LockMode::Shared => { - let _waiter_guard = WaiterCounterGuard::new(state.clone(), LockMode::Shared); - timeout(wait, state.optimized_notify.wait_for_read()).await - } - LockMode::Exclusive => { - let _waiter_guard = WaiterCounterGuard::new(state.clone(), LockMode::Exclusive); - timeout(wait, state.optimized_notify.wait_for_write()).await - } - }; - - // A capped-wait elapse is not a real timeout: loop back and re-try the - // acquisition. The deadline check at the top of the loop is the single - // source of truth for returning `Timeout`. - let _ = wait_result; + let _reader = WaitingReader::new(&state); + // A capped wait only re-polls. The request deadline above decides timeout. + let _ = timeout(wait, state.optimized_notify.wait_for_read()).await; retry_count += 1; } } diff --git a/crates/lock/src/fast_lock/state.rs b/crates/lock/src/fast_lock/state.rs index ce0e852eb5..cf8bdd9976 100644 --- a/crates/lock/src/fast_lock/state.rs +++ b/crates/lock/src/fast_lock/state.rs @@ -121,7 +121,7 @@ impl AtomicLockState { /// Try to acquire exclusive lock (fast path) pub fn try_acquire_exclusive(&self) -> bool { - if self.try_acquire_exclusive_raw() { + if self.try_acquire_exclusive_raw(0) { self.update_access_time(); true } else { @@ -129,19 +129,13 @@ impl AtomicLockState { } } - fn try_acquire_exclusive_raw(&self) -> bool { + fn try_acquire_exclusive_raw(&self, blocked_waiters: u64) -> bool { loop { let current = self.state.load(Ordering::Acquire); - // Only ownership bits may block acquisition: no writer flag, no - // active readers. The waiting counters are preserved, not - // required to be zero — demanding a fully-zero word means a lock - // with registered waiters can be acquired by *no one*, including - // the waiters themselves (each sees the others' registration), - // so contended acquisition only succeeds in windows where every - // waiter happens to be unregistered. `try_acquire_shared` above - // already masks correctly; this mirrors it. - if (current & (WRITER_FLAG_MASK | READERS_MASK)) != 0 { + // Admitted writers ignore waiters. A new writer also tests the + // queued-writer bits in the same CAS that claims ownership. + if (current & (WRITER_FLAG_MASK | READERS_MASK | blocked_waiters)) != 0 { return false; } @@ -356,7 +350,7 @@ pub struct ObjectLockState { // First cache line: Most frequently accessed data /// Atomic state for fast operations pub atomic_state: AtomicLockState, - pub(super) publication: OnceLock>, + pub(super) admission: OnceLock>, // Second cache line: Notification mechanisms /// Notification for readers (traditional) @@ -400,7 +394,7 @@ impl ObjectLockState { pub fn new() -> Self { Self { atomic_state: AtomicLockState::new(), - publication: OnceLock::new(), + admission: OnceLock::new(), read_notify: Notify::new(), write_notify: Notify::new(), optimized_notify: OptimizedNotify::new(), @@ -451,7 +445,15 @@ impl ObjectLockState { /// Try fast path exclusive lock acquisition pub fn try_acquire_exclusive_fast(&self, owner: &Arc, lock_timeout: Duration) -> bool { - if !self.atomic_state.try_acquire_exclusive_raw() { + self.try_acquire_exclusive_with_mask(owner, lock_timeout, 0) + } + + pub(super) fn try_acquire_unqueued_exclusive(&self, owner: &Arc, lock_timeout: Duration) -> bool { + self.try_acquire_exclusive_with_mask(owner, lock_timeout, WRITERS_WAITING_MASK) + } + + fn try_acquire_exclusive_with_mask(&self, owner: &Arc, lock_timeout: Duration, blocked_waiters: u64) -> bool { + if !self.atomic_state.try_acquire_exclusive_raw(blocked_waiters) { return false; } @@ -476,7 +478,7 @@ impl ObjectLockState { } else { shared.remove(pos); } - if let Some(queue) = self.publication.get() { + if let Some(queue) = self.admission.get() { queue.changed.notify_waiters(); } if shared.is_empty() { @@ -509,7 +511,7 @@ impl ObjectLockState { if self.atomic_state.release_exclusive() { *current = None; drop(current); - if let Some(queue) = self.publication.get() { + if let Some(queue) = self.admission.get() { queue.changed.notify_waiters(); } // Notify waiters using optimized system - prefer writers over readers diff --git a/crates/lock/src/fast_lock/tests.rs b/crates/lock/src/fast_lock/tests.rs index a0ad423dea..3b3e0939f3 100644 --- a/crates/lock/src/fast_lock/tests.rs +++ b/crates/lock/src/fast_lock/tests.rs @@ -32,6 +32,61 @@ mod fast_lock_tests { FastObjectLockManager::with_config(config) } + #[tokio::test] + async fn ordinary_writers_cannot_barge_ahead_of_waiters() { + let manager = create_test_manager(); + let key = ObjectKey::new("bucket", "ordinary"); + let holder = manager.acquire_write_lock(key.clone(), "holder").await.expect("hold the key"); + let first = manager.acquire_write_lock(key.clone(), "first"); + let second = manager.acquire_write_lock(key.clone(), "second"); + tokio::pin!(first, second); + assert!(futures::poll!(&mut first).is_pending()); + assert!(futures::poll!(&mut second).is_pending()); + drop(holder); + + // Poll the newcomer before allowing a notified waiter to run. + let newcomer = manager.acquire_write_lock(key, "newcomer"); + tokio::pin!(newcomer); + assert!(futures::poll!(&mut newcomer).is_pending(), "new writer overtook queued writers"); + assert!(futures::poll!(&mut second).is_pending(), "second writer overtook first"); + let first = first.await.expect("first writer progresses"); + assert!(futures::poll!(&mut newcomer).is_pending()); + drop(first); + assert!(futures::poll!(&mut newcomer).is_pending(), "new writer overtook second"); + drop(second.await.expect("second writer progresses")); + drop(newcomer.await.expect("last writer progresses")); + assert_eq!(manager.current_lock_counts(), (0, 0)); + } + + #[tokio::test] + async fn ordinary_writers_cannot_be_bypassed_by_a_batch_after_cancellation() { + for all_or_nothing in [false, true] { + let manager = create_test_manager(); + let key = ObjectKey::new("bucket", "ordinary"); + let holder = manager.acquire_read_lock(key.clone(), "reader").await.expect("hold the key"); + let mut cancelled = Box::pin(manager.acquire_write_lock(key.clone(), "cancelled")); + let writer = manager.acquire_write_lock(key.clone(), "survivor"); + tokio::pin!(writer); + assert!(futures::poll!(&mut cancelled).is_pending()); + assert!(futures::poll!(&mut writer).is_pending()); + drop(cancelled); + drop(holder); + + let batch = manager.acquire_locks_batch( + crate::fast_lock::BatchLockRequest::new("batch") + .add_write_lock(key) + .with_all_or_nothing(all_or_nothing), + ); + tokio::pin!(batch); + assert!(futures::poll!(&mut batch).is_pending(), "batch overtook the surviving writer"); + drop(writer.await.expect("writer takes cancelled head's place")); + let result = batch.await; + assert!(result.all_acquired); + drop(result); + assert_eq!(manager.current_lock_counts(), (0, 0)); + } + } + #[test] fn try_with_config_returns_error_for_invalid_shard_count() { let config = LockConfig {