merge: include verified object writer ordering and batch preparation

This commit is contained in:
overtrue
2026-12-02 21:08:10 +08:00
9 changed files with 383 additions and 124 deletions
+15 -1
View File
@@ -131,12 +131,26 @@ const PART_METADATA_READ_CONCURRENCY: usize = 8;
const DELETE_VERSION_PREPARE_CONCURRENCY: usize = 8;
fn delete_version_batch_concurrency(versions: &[FileInfoVersions], opts: &DeleteOptions) -> usize {
if !cfg!(target_os = "linux") || !opts.recoverable_delete || opts.undo_write || opts.undo_delete || versions.len() < 2 {
if !cfg!(any(target_os = "linux", target_os = "macos"))
|| !opts.recoverable_delete
|| opts.undo_write
|| opts.undo_delete
|| versions.len() < 2
{
return 1;
}
let mut names = HashSet::with_capacity(versions.len());
for version in versions {
let name = version.name.as_str();
// A macOS volume may fold case and normalize Unicode. Only schedule
// names from an unambiguous on-disk alphabet concurrently there.
#[cfg(target_os = "macos")]
if !name
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'/' | b'.' | b'-' | b'_'))
{
return 1;
}
if name.split('/').any(|segment| matches!(segment, "" | "." | "..")) || !names.insert(name) {
return 1;
}
@@ -4633,6 +4633,12 @@ mod tests {
vec!["a//b", "a/b"],
vec!["a/./b", "a/b"],
vec!["a/../b", "b"],
#[cfg(target_os = "macos")]
vec!["object", "OBJECT"],
#[cfg(target_os = "macos")]
vec!["prefix", "Prefix/child"],
#[cfg(target_os = "macos")]
vec!["café", "cafe\u{301}"],
] {
let groups: Vec<_> = names
.into_iter()
@@ -4654,7 +4660,7 @@ mod tests {
..Default::default()
})
.collect();
let expected = if cfg!(target_os = "linux") {
let expected = if cfg!(any(target_os = "linux", target_os = "macos")) {
super::super::DELETE_VERSION_PREPARE_CONCURRENCY
} else {
1
@@ -4679,7 +4685,7 @@ mod tests {
}
}
#[cfg(target_os = "linux")]
#[cfg(any(target_os = "linux", target_os = "macos"))]
#[tokio::test]
async fn delete_recovery_batch_prepares_independent_keys_while_one_metadata_lease_is_held() {
let (temp, disk, info, _) = fixture().await;
@@ -4696,7 +4702,8 @@ mod tests {
fs::write(corrupt_root.join(STORAGE_FORMAT_FILE), b"invalid xl.meta")
.await
.expect("corrupt source");
let held = os::acquire_metadata_mutation_lease(&temp.path().join("recovery/object"), None).await;
let object_path = disk.get_object_path("recovery", "object").expect("object mutation path");
let held = os::acquire_metadata_mutation_lease(&object_path, None).await;
let groups = ["object", "corrupt", "healthy"]
.into_iter()
.map(|name| super::super::FileInfoVersions {
+60
View File
@@ -21817,6 +21817,66 @@ mod tests {
}
}
#[tokio::test]
#[serial_test::serial(storage_class_env)]
async fn bulk_delete_releases_completed_keys_while_an_unrelated_disk_transaction_waits() {
let temp = tempfile::tempdir().expect("temporary store");
let root = temp.path().canonicalize().expect("canonical disk root");
let (_ctx, store, _shutdown) =
without_storage_class_env(build_isolated_test_store(&root, "batch-key-lifetime", &[1])).await;
crate::bucket::metadata_sys::init_bucket_metadata_sys(store.clone(), Vec::new()).await;
let bucket = format!("batch-lock-{}", uuid::Uuid::new_v4());
store
.make_bucket(&bucket, &MakeBucketOptions::default())
.await
.expect("create bucket");
for key in ["a-done", "z-held"] {
let mut body = PutObjReader::from_vec(b"before delete".to_vec());
store
.put_object(&bucket, key, &mut body, &ObjectOptions::default())
.await
.expect("seed object");
}
let disk = root.join("pool0/set0/disk0").join(&bucket);
let held_path = disk.join("z-held");
let done_meta = disk.join("a-done/xl.meta");
assert!(done_meta.is_file() && held_path.join("xl.meta").is_file());
let held = crate::disk::os::acquire_metadata_mutation_lease(&held_path, None).await;
let keys: Vec<_> = std::iter::once("a-done".to_owned())
.chain((0..32).map(|i| format!("middle-{i:02}")))
.chain(std::iter::once("z-held".to_owned()))
.collect();
let objects = keys
.iter()
.map(|name| crate::storage_api_contracts::object::ObjectToDelete {
object_name: name.clone(),
..Default::default()
})
.collect();
let service = Arc::clone(&store);
let name = bucket.clone();
let deletion = tokio::spawn(async move { service.delete_objects(&name, objects, ObjectOptions::default()).await });
let completed_key = tokio::time::timeout(Duration::from_secs(12), async {
while tokio::fs::try_exists(&done_meta).await.expect("observe completed key") {
tokio::time::sleep(Duration::from_millis(10)).await;
}
let lock = store.handle_new_ns_lock(&bucket, "a-done").await.expect("completed key lock");
lock.get_write_lock_quiet(Duration::from_secs(30))
.await
.expect("reuse completed key");
})
.await;
assert!(held_path.join("xl.meta").is_file(), "the held object must stay intact");
drop(held);
let (deleted, errors) = deletion.await.expect("join bulk delete");
assert!(errors.iter().all(Option::is_none), "{errors:?}");
assert_eq!(
deleted.iter().map(|v| &v.object_name).collect::<Vec<_>>(),
keys.iter().collect::<Vec<_>>()
);
assert!(completed_key.is_ok(), "a stalled disk transaction kept an unrelated completed key locked");
}
// #6898: a DeleteObjects request dropped between the per-disk commit and the
// cleanup pass (client disconnect) must not leave metadata-less residue.
#[tokio::test]
+166 -11
View File
@@ -2793,6 +2793,54 @@ async fn await_conditional_capability_set_probe_gate(bucket: &str) -> Result<()>
Ok(())
}
// Keep every version and duplicate receipt for one name under the same guard.
// Cross-key receipts can complete independently when their on-disk paths are disjoint.
const BATCH_DELETE_KEYS_PER_GROUP: usize = 16;
#[derive(Default)]
struct BatchDeleteLockGroup {
indices: Vec<usize>,
objects: Vec<ObjectToDelete>,
guards: Vec<ObjectLockDiagGuard>,
}
fn attach_batch_delete_lock_fence(opts: &mut ObjectOptions, guards: &[ObjectLockDiagGuard]) {
opts.no_lock = true;
for signal in guards.iter().filter_map(ObjectLockDiagGuard::lock_lost_signal) {
opts.add_namespace_lock_lost_signal(signal);
}
opts.ensure_namespace_lock_fence();
}
fn ordinary_delete_lock_groups(objects: &[ObjectToDelete]) -> Option<HashMap<String, usize>> {
if objects.len() <= BATCH_DELETE_KEYS_PER_GROUP
|| objects
.iter()
.any(|item| item.delete_condition.is_some() || item.expected_identity.is_some())
{
return None;
}
let names = sorted_unique_delete_object_names(objects);
if names.len() <= BATCH_DELETE_KEYS_PER_GROUP {
return None;
}
let mut groups = HashMap::with_capacity(names.len());
for (index, name) in names.into_iter().enumerate() {
// Sorting places an ancestor before its descendants. A case-folding
// filesystem or an encoded directory object must not bypass this check.
if !name
.bytes()
.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'/' | b'.' | b'-' | b'_'))
|| name.split('/').any(|part| matches!(part, "" | "." | ".."))
|| name.match_indices('/').any(|(end, _)| groups.contains_key(&name[..end]))
{
return None;
}
groups.insert(name.to_owned(), index / BATCH_DELETE_KEYS_PER_GROUP);
}
Some(groups)
}
struct BatchDeletePhasePlan<'a> {
/// Unique input positions in request order.
indices: &'a [usize],
@@ -3752,12 +3800,7 @@ impl ECStore {
"Bulk delete namespace lock acquisition failed for some keys"
);
}
opts.no_lock = true;
for signal in guards.iter().filter_map(ObjectLockDiagGuard::lock_lost_signal) {
opts.add_namespace_lock_lost_signal(signal);
}
opts.ensure_namespace_lock_fence();
attach_batch_delete_lock_fence(opts, &guards);
Ok((guards, failures))
}
@@ -6767,23 +6810,104 @@ impl ECStore {
if current_bucket_incarnation_id.is_some() {
pause_delete_after_object_lock_snapshot(bucket).await;
}
if self.single_pool()
&& !opts.no_lock
&& !is_meta_bucketname(bucket)
&& let Some(group_for_key) = ordinary_delete_lock_groups(&objects)
{
return self
.delete_independent_object_groups(bucket, objects, opts, group_for_key)
.await;
}
self.delete_batch_under_bucket_guards(bucket, objects, opts).await
}
async fn delete_independent_object_groups(
&self,
bucket: &str,
objects: Vec<ObjectToDelete>,
opts: ObjectOptions,
group_for_key: HashMap<String, usize>,
) -> (Vec<DeletedObject>, Vec<Option<Error>>, Vec<Option<DeleteAccounting>>) {
// Admit the whole request once so every peer sees the same lock deadline.
// Each group then owns just its guards through disk commit and rollback.
let mut admission = opts.clone();
let (guards, failures) = match self
.acquire_delete_objects_write_locks(bucket, &objects, &mut admission)
.await
{
Ok(result) => result,
Err(error) => return return_batch_delete_lock_error_with_accounting(&objects, error),
};
let count = objects.len();
let mut groups: Vec<BatchDeleteLockGroup> = (0..group_for_key.len().div_ceil(BATCH_DELETE_KEYS_PER_GROUP))
.map(|_| BatchDeleteLockGroup::default())
.collect();
for (index, object) in objects.into_iter().enumerate() {
let group = &mut groups[group_for_key[&object.object_name]];
group.indices.push(index);
group.objects.push(object);
}
for guard in guards {
let (_, name) = guard
.write_key
.as_ref()
.expect("batch acquisition binds every guard to a requested key");
groups[group_for_key[name]].guards.push(guard);
}
let work = futures::stream::iter(groups)
.map(|group| {
let mut options = opts.clone();
let failures = &failures;
async move {
attach_batch_delete_lock_fence(&mut options, &group.guards);
let result = self
.delete_batch_with_object_guards(bucket, group.objects, options, group.guards, failures)
.await;
(group.indices, result)
}
})
.buffer_unordered(2);
futures::pin_mut!(work);
let mut deleted = vec![DeletedObject::default(); count];
let mut errors = vec![None; count];
let mut receipts = vec![None; count];
while let Some((indices, (items, outcomes, accounting))) = work.next().await {
for (((index, item), outcome), receipt) in indices.into_iter().zip(items).zip(outcomes).zip(accounting) {
deleted[index] = item;
errors[index] = outcome;
receipts[index] = receipt;
}
}
(deleted, errors, receipts)
}
async fn delete_batch_under_bucket_guards(
&self,
bucket: &str,
objects: Vec<ObjectToDelete>,
mut opts: ObjectOptions,
) -> (Vec<DeletedObject>, Vec<Option<Error>>, Vec<Option<DeleteAccounting>>) {
let (guards, failures) = match self.acquire_delete_objects_write_locks(bucket, &objects, &mut opts).await {
Ok(result) => result,
Err(error) => return return_batch_delete_lock_error_with_accounting(&objects, error),
};
self.delete_batch_with_object_guards(bucket, objects, opts, guards, &failures)
.await
}
async fn delete_batch_with_object_guards(
&self,
bucket: &str,
mut objects: Vec<ObjectToDelete>,
mut opts: ObjectOptions,
object_lock_guards: Vec<ObjectLockDiagGuard>,
object_lock_failures: &HashMap<String, StorageError>,
) -> (Vec<DeletedObject>, Vec<Option<Error>>, Vec<Option<DeleteAccounting>>) {
let mut del_objects = vec![DeletedObject::default(); objects.len()];
let mut del_errs = vec![None; objects.len()];
let mut accounting = vec![None; objects.len()];
let (object_lock_guards, object_lock_failures) =
match self.acquire_delete_objects_write_locks(bucket, &objects, &mut opts).await {
Ok(result) => result,
Err(err) => return return_batch_delete_lock_error_with_accounting(objects.as_slice(), err),
};
// Lock outcomes are per key: a locked-out key fails alone and the rest
// of the batch proceeds, matching the set layer's per-key lock errors.
if !object_lock_failures.is_empty() {
@@ -11856,6 +11980,37 @@ mod tests {
assert!(!versions.objects.iter().any(|entry| entry.version_id == old.version_id));
}
#[test]
fn batch_delete_lock_groups_keep_versions_together_and_fall_back_for_aliases() {
let mut objects: Vec<_> = (0..=BATCH_DELETE_KEYS_PER_GROUP)
.map(|i| ObjectToDelete {
object_name: format!("dir/key-{i:02}"),
..Default::default()
})
.collect();
assert!(ordinary_delete_lock_groups(&objects[..BATCH_DELETE_KEYS_PER_GROUP]).is_none());
let mut another_version = objects[0].clone();
another_version.version_id = Some(Uuid::new_v4());
objects.push(another_version);
let groups = ordinary_delete_lock_groups(&objects).expect("independent keys");
assert_eq!(groups.len(), BATCH_DELETE_KEYS_PER_GROUP + 1);
assert_eq!(groups[&objects[0].object_name], groups[&objects.last().unwrap().object_name]);
assert_ne!(groups[&objects[0].object_name], groups[&objects[BATCH_DELETE_KEYS_PER_GROUP].object_name]);
for name in ["dir", "dir/KEY-01", "dir//a", "dir/./a", "dir/../a", "dir/café"] {
objects.last_mut().unwrap().object_name = name.to_owned();
assert!(ordinary_delete_lock_groups(&objects).is_none(), "{name}");
}
let last = objects.last_mut().unwrap();
last.object_name = "independent".to_owned();
last.delete_condition = Some(crate::storage_api_contracts::object::DeleteObjectCondition::Exists);
assert!(ordinary_delete_lock_groups(&objects).is_none());
let last = objects.last_mut().unwrap();
last.delete_condition = None;
*last = last.clone().with_expected_identity(None, None, false);
assert!(ordinary_delete_lock_groups(&objects).is_none());
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn batch_delete_rejects_dot_segments_and_keeps_valid_result_positions() {
let bucket = "batch-delete-key-validation";
+1 -1
View File
@@ -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;
+9 -12
View File
@@ -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<VecDeque<(Arc<()>, LockMode)>>,
pub(super) changed: Notify,
}
pub(super) struct PublicationTicket {
pub(super) struct AdmissionTicket {
state: Arc<ObjectLockState>,
pub(super) queue: Arc<PublicationQueue>,
pub(super) queue: Arc<AdmissionQueue>,
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<ObjectLockState>, mode: LockMode) -> Option<Self> {
@@ -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();
+49 -80
View File
@@ -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<HashMap<u64, Option<ActiveGuardInfo>>>,
}
/// 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<ObjectLockState>,
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<ObjectLockState>, 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<PublicationTicket> {
fn admission_ticket(&self, request: &ObjectLockRequest) -> Option<AdmissionTicket> {
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;
}
}
+18 -16
View File
@@ -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<Arc<super::publication::PublicationQueue>>,
pub(super) admission: OnceLock<Arc<super::publication::AdmissionQueue>>,
// 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<str>, 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<str>, 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<str>, 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
+55
View File
@@ -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 {