Compare commits

..

3 Commits

Author SHA1 Message Date
唐小鸭 5a5acedbee Merge remote-tracking branch 'origin/main' into fix/replication-delete-worker-retry 2026-12-01 12:17:18 +08:00
唐小鸭 51bd41a30b Merge remote-tracking branch 'origin/main' into fix/replication-delete-worker-retry 2026-11-30 11:10:12 +08:00
唐小鸭 49f01af16d fix(replication): replay deletes deferred by a held source lock
A live delete replication that cannot take the source object lock was dropped: the worker discarded the outcome, and the two lock skips before the target call were only logged at debug. A bulk delete keeps its key locks until the whole batch commits and keeps running after its client disconnects, so a retried bulk delete of the same keys made earlier markers lose the five second lock wait and never reach the target, or reach it without the result being recorded on the source.

Report how an attempt ended. When a source-side lock or read kept it from running, or from persisting its result, the worker journals the delete so the periodic MRF replay drives it again. Target failures stay with the persisted state and the scanner as before, so an unreachable target does not fill the journal. The three source-deferred skips now log at warn.
2026-11-29 22:59:11 +08:00
6 changed files with 210 additions and 439 deletions
@@ -38,8 +38,8 @@ use super::replication_resync_boundary::{
decode_resync_file, encode_mrf_file, should_auto_resume_resync,
};
use super::replication_resyncer::{
ReplicationResyncer, get_heal_replicate_object_info, replicate_delete, replicate_delete_with_outcome, replicate_object,
replicate_object_with_outcome, update_resync_status_cas,
DeleteReplicationAttempt, ReplicationResyncer, get_heal_replicate_object_info, replicate_delete_attempt,
replicate_delete_with_outcome, replicate_object, replicate_object_with_outcome, update_resync_status_cas,
};
use super::replication_state::ReplicationStats;
use super::replication_storage_boundary::{
@@ -1329,12 +1329,14 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let storage = self.storage.clone();
let stats = self.stats.clone();
let in_flight = self.in_flight.clone();
let mrf_save_tx = self.mrf_save_tx.clone();
let handle = tokio::spawn(async move {
let mut rx = rx;
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
.await;
}
});
@@ -1389,12 +1391,14 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let stats = self.stats.clone();
let storage = self.storage.clone();
let in_flight = self.in_flight.clone();
let mrf_save_tx = self.mrf_save_tx.clone();
let handle = tokio::spawn(async move {
let mut rx = rx;
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
.await;
}
});
@@ -1434,6 +1438,7 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let stats = self.stats.clone();
let storage = self.storage.clone();
let in_flight = self.in_flight.clone();
let mrf_save_tx = self.mrf_save_tx.clone();
let mrf_rx = Arc::clone(&self.mrf_replica_rx);
let handle = tokio::spawn(async move {
@@ -1453,7 +1458,8 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
let Some(operation) = operation else { break };
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone()).await;
process_replication_operation(operation, stats.clone(), storage.clone(), in_flight.clone(), &mrf_save_tx)
.await;
}
});
self.task_handles.lock().await.push(handle);
@@ -1935,7 +1941,14 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
) {
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), self.storage.clone(), self.in_flight.clone()).await;
process_replication_operation(
operation,
stats.clone(),
self.storage.clone(),
self.in_flight.clone(),
&self.mrf_save_tx,
)
.await;
}
}
@@ -1953,7 +1966,8 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
) {
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), storage.clone(), self.in_flight.clone()).await;
process_replication_operation(operation, stats.clone(), storage.clone(), self.in_flight.clone(), &self.mrf_save_tx)
.await;
}
}
@@ -1970,7 +1984,14 @@ impl<S: ReplicationStorage> ReplicationPool<S> {
) {
while let Some(operation) = rx.recv().await {
let _active = ActiveWorkerGuard::new(active_counter.clone());
process_replication_operation(operation, stats.clone(), self.storage.clone(), self.in_flight.clone()).await;
process_replication_operation(
operation,
stats.clone(),
self.storage.clone(),
self.in_flight.clone(),
&self.mrf_save_tx,
)
.await;
}
}
@@ -2539,6 +2560,7 @@ async fn process_replication_operation<S: ReplicationStorage>(
stats: Arc<ReplicationStats>,
storage: Arc<S>,
in_flight: Arc<ReplicationInFlight>,
mrf_save_tx: &Sender<MrfReplicateEntry>,
) {
match operation {
ReplicationOperation::Object(obj_info) => {
@@ -2548,7 +2570,14 @@ async fn process_replication_operation<S: ReplicationStorage>(
}
ReplicationOperation::Delete(del_info) => {
let _backlog = ReplicationBacklogGuard::for_delete(stats, del_info.as_ref());
replicate_delete(*del_info, storage).await;
// The delete request already succeeded, so a source lock that is
// still held (a bulk delete keeps its key locks until the whole
// batch commits) must not cost the replication: journal it for
// the next MRF replay.
let retry_entry = del_info.to_mrf_entry();
if replicate_delete_attempt(*del_info, storage).await == DeleteReplicationAttempt::SourceDeferred {
queue_mrf_save_entry(mrf_save_tx, retry_entry, "delete_source_deferred").await;
}
}
}
}
@@ -4506,6 +4535,102 @@ mod tests {
}
}
/// Runs one live delete through the worker and returns what it journaled for MRF replay.
async fn delete_worker_journal(
delete: DeletedObjectReplicationInfo,
writeback_error: EcstoreError,
) -> Vec<MrfReplicateEntry> {
let shared = empty_resync_shared_state();
*shared.delete_error.lock().expect("delete error lock should not be poisoned") = writeback_error;
let storage = Arc::new(LoadResyncNodeStore::new("delete-worker-journal", shared));
let (mrf_save_tx, mut mrf_save_rx) = mpsc::channel(4);
process_replication_operation(
ReplicationOperation::Delete(Box::new(delete)),
Arc::new(ReplicationStats::new()),
storage,
Arc::new(ReplicationInFlight::default()),
&mrf_save_tx,
)
.await;
drop(mrf_save_tx);
let mut journaled = Vec::new();
while let Some(entry) = mrf_save_rx.recv().await {
journaled.push(entry);
}
journaled
}
fn purged_on_target_delete(
arn: &str,
version_id: Uuid,
target_status: VersionPurgeStatusType,
) -> DeletedObjectReplicationInfo {
DeletedObjectReplicationInfo {
bucket: "source".to_string(),
delete_object: ReplicationDeletedObject {
object_name: "purged".to_string(),
version_id: Some(version_id),
replication_state: Some(ReplicationState {
replicate_decision_str: test_replicate_decision(&[arn]).to_string(),
purge_targets: HashMap::from([(arn.to_string(), target_status)]),
..Default::default()
}),
..Default::default()
},
op_type: ReplicationType::Delete,
..Default::default()
}
}
#[tokio::test]
async fn delete_worker_journals_a_delete_whose_source_writeback_lost_the_object_lock() {
let arn = "arn:test";
let version_id = Uuid::new_v4();
// A bulk delete of the same key still holds the object lock.
let lock_timeout = EcstoreError::Lock(rustfs_lock::LockError::internal(
"Lock acquisition timeout for resource 'source/purged@latest' after 5s".to_string(),
));
let journaled =
delete_worker_journal(purged_on_target_delete(arn, version_id, VersionPurgeStatusType::Complete), lock_timeout).await;
assert_eq!(
journaled.len(),
1,
"a delete whose result never reached the source must be kept for replay"
);
let entry = &journaled[0];
assert_eq!((entry.bucket.as_str(), entry.object.as_str()), ("source", "purged"));
assert_eq!(entry.version_id, Some(version_id));
assert_eq!(entry.op, MrfOpKind::Delete);
assert_eq!(entry.target_arns, vec![arn.to_string()]);
}
#[tokio::test]
async fn delete_worker_does_not_journal_deletes_other_paths_own() {
let arn = "arn:test";
let source_gone = || EcstoreError::ObjectNotFound("source".to_string(), "purged".to_string());
let completed = delete_worker_journal(
purged_on_target_delete(arn, Uuid::new_v4(), VersionPurgeStatusType::Complete),
source_gone(),
)
.await;
assert!(completed.is_empty(), "a completed delete must not be replayed");
let target_pending = delete_worker_journal(
purged_on_target_delete(arn, Uuid::new_v4(), VersionPurgeStatusType::Pending),
source_gone(),
)
.await;
assert!(
target_pending.is_empty(),
"unfinished target work is recorded in the source state for the scanner, not journaled per delete"
);
}
#[tokio::test]
async fn delete_worker_preserves_persisted_admission_without_live_config() {
let arn = "arn:test";
@@ -2422,12 +2422,40 @@ pub async fn replicate_delete<S: ReplicationStorage>(dobj: DeletedObjectReplicat
let _ = replicate_delete_with_outcome(dobj, storage).await;
}
/// How one delete replication attempt ended.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DeleteReplicationAttempt {
/// Every admitted target finished and the source state was persisted.
Completed,
/// The attempt did not finish for a reason another path already owns: a
/// target failure is recorded in the persisted state for the scanner, and
/// a force delete or delete-marker purge journals its own intent.
Unfinished,
/// A source-side lock or read kept the attempt from running, or from
/// persisting its result. Nothing durable records that, so the caller must
/// keep the delete for a later attempt.
SourceDeferred,
}
impl DeleteReplicationAttempt {
fn from_finished(finished: bool) -> Self {
if finished { Self::Completed } else { Self::Unfinished }
}
}
pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
dobj: DeletedObjectReplicationInfo,
storage: Arc<S>,
) -> bool {
replicate_delete_attempt(dobj, storage).await == DeleteReplicationAttempt::Completed
}
pub(crate) async fn replicate_delete_attempt<S: ReplicationStorage>(
dobj: DeletedObjectReplicationInfo,
storage: Arc<S>,
) -> DeleteReplicationAttempt {
if dobj.delete_object.force_delete {
return replicate_force_delete_to_targets(&dobj, storage).await;
return DeleteReplicationAttempt::from_finished(replicate_force_delete_to_targets(&dobj, storage).await);
}
let bucket = dobj.bucket.clone();
@@ -2472,7 +2500,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return false;
return DeleteReplicationAttempt::Unfinished;
}
};
let target_arns = dobj.admitted_target_arns();
@@ -2480,7 +2508,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
// Batch expiry can return an empty state after removing the source.
// It owes no remote work or local writeback. Persisted target admission
// must still be honored even when the live configuration is gone.
return true;
return DeleteReplicationAttempt::Completed;
}
if dobj.delete_object.delete_marker
@@ -2502,7 +2530,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
reason = "source_not_delete_marker",
"Skipping stale delete-marker replication"
);
return true;
return DeleteReplicationAttempt::Completed;
}
Err(err) if is_err_object_not_found(&err) || is_err_version_not_found(&err) => {
debug!(
@@ -2520,7 +2548,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
// purge-intent replay landing here on purpose). Purge instead
// of just skipping; the result decides whether an MRF replay
// may acknowledge the entry.
return purge_stale_delete_marker_targets(&bucket, &dobj).await;
return DeleteReplicationAttempt::from_finished(purge_stale_delete_marker_targets(&bucket, &dobj).await);
}
Err(err) => {
// A transient source error (lock timeout, IO error) must not
@@ -2529,7 +2557,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
// target mint one more delete marker (rustfs#6823). Fail the
// entry without touching the target; the MRF replay / heal
// scanner retries once the source is readable again.
debug!(
warn!(
event = EVENT_REPLICATION_DELETE_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
@@ -2554,7 +2582,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return false;
return DeleteReplicationAttempt::SourceDeferred;
}
}
}
@@ -2565,7 +2593,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
{
Ok(ns_lock) => ns_lock,
Err(e) => {
debug!(
warn!(
event = EVENT_REPLICATION_DELETE_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
@@ -2589,14 +2617,14 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return false;
return DeleteReplicationAttempt::SourceDeferred;
}
};
let _lock_guard = match ns_lock.get_write_lock(ReplicationLockTiming::acquire_timeout()).await {
Ok(lock_guard) => lock_guard,
Err(e) => {
debug!(
warn!(
event = EVENT_REPLICATION_DELETE_SKIPPED,
component = LOG_COMPONENT_ECSTORE,
subsystem = LOG_SUBSYSTEM_REPLICATION_RESYNC,
@@ -2620,7 +2648,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
user_agent: "Internal: [Replication]".to_string(),
..Default::default()
});
return false;
return DeleteReplicationAttempt::SourceDeferred;
}
};
@@ -2858,7 +2886,12 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
}
};
replicate_delete_outcome(
if !state_persisted {
// The targets were driven, but the result never reached the source
// metadata, so a scanner pass would still see the pre-attempt state.
return DeleteReplicationAttempt::SourceDeferred;
}
DeleteReplicationAttempt::from_finished(replicate_delete_outcome(
expected_targets,
rinfos.targets.len(),
state_persisted,
@@ -2866,7 +2899,7 @@ pub(crate) async fn replicate_delete_with_outcome<S: ReplicationStorage>(
// error returns early above instead of replicating unverified.
true,
&replication_status,
)
))
}
/// Reads the source version addressed by `delete_marker_version_id` so a
+13 -291
View File
@@ -28,10 +28,6 @@ use crate::{
/// Default shard count for guard storage (must be power of 2)
const DEFAULT_GUARD_SHARD_COUNT: usize = 64;
/// Default interval for reaping expired local lease guards.
/// Kept independent of `fast_lock::CLEANUP_INTERVAL` (which sweeps idle state pools)
/// so expired leases are released promptly even when the cluster is quiescent.
pub(crate) const DEFAULT_LEASE_REAPER_INTERVAL: Duration = Duration::from_secs(1);
const EVENT_NAMESPACE_LOCK_ACQUIRE: &str = "namespace_lock_acquire";
const EVENT_NAMESPACE_LOCK_RELEASE: &str = "namespace_lock_release";
const EVENT_LOCK_GUARD_RECLAIMED: &str = "lock_guard_reclaimed";
@@ -471,7 +467,7 @@ impl LocalClient {
let guard_storage: Vec<GuardShard> = (0..shard_count).map(|_| Arc::new(GuardRegistry::default())).collect();
Self::with_storage(Arc::new(guard_storage), None, DEFAULT_LEASE_REAPER_INTERVAL)
Self::with_storage(Arc::new(guard_storage), None, crate::fast_lock::CLEANUP_INTERVAL)
}
fn with_storage(guard_storage: GuardStorage, manager: Option<Arc<GlobalLockManager>>, reaper_interval: Duration) -> Self {
@@ -522,7 +518,7 @@ impl LocalClient {
let guard_storage = (0..DEFAULT_GUARD_SHARD_COUNT)
.map(|_| Arc::new(GuardRegistry::default()))
.collect();
Self::with_storage(Arc::new(guard_storage), Some(manager), DEFAULT_LEASE_REAPER_INTERVAL)
Self::with_storage(Arc::new(guard_storage), Some(manager), crate::fast_lock::CLEANUP_INTERVAL)
}
#[cfg(test)]
@@ -565,35 +561,25 @@ impl LocalClient {
reclaimed_for_resource
}
async fn reclaim_expired_guards(storage: &GuardStorage) -> usize {
let mut total_reclaimed = 0;
async fn extract_expired_guards(storage: &GuardStorage) -> Vec<LocalGuardEntry> {
let mut expired_entries = Vec::new();
for shard in storage.iter() {
if !shard.read().await.sweep_due() {
continue;
}
let expired_entries = {
let mut guards = shard.write().await;
guards.extract_expired()
};
// Drop physical guards outside the shard lock immediately so contention on a later
// shard cannot delay releasing expired guards extracted from earlier shards.
total_reclaimed += Self::release_reclaimed_guards_unlogged(expired_entries);
let mut guards = shard.write().await;
expired_entries.extend(guards.extract_expired());
}
Self::log_reclaimed_guards(total_reclaimed);
total_reclaimed
expired_entries
}
fn release_reclaimed_guards_unlogged(entries: impl IntoIterator<Item = LocalGuardEntry>) -> usize {
fn release_reclaimed_guards(entries: impl IntoIterator<Item = LocalGuardEntry>) -> usize {
let mut reclaimed = 0;
for mut entry in entries {
let _ = entry.guard.release();
rustfs_io_metrics::record_lock_reclaimed();
reclaimed += 1;
}
reclaimed
}
fn log_reclaimed_guards(reclaimed: usize) {
if reclaimed > 0 {
tracing::debug!(
event = EVENT_LOCK_GUARD_RECLAIMED,
@@ -604,11 +590,6 @@ impl LocalClient {
"Expired lock guards reclaimed"
);
}
}
fn release_reclaimed_guards(entries: impl IntoIterator<Item = LocalGuardEntry>) -> usize {
let reclaimed = Self::release_reclaimed_guards_unlogged(entries);
Self::log_reclaimed_guards(reclaimed);
reclaimed
}
@@ -620,13 +601,13 @@ impl LocalClient {
let interval = self.reaper_interval;
tokio::spawn(async move {
let mut ticker = tokio::time::interval(interval);
ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
loop {
ticker.tick().await;
let Some(storage) = storage.upgrade() else {
break;
};
Self::reclaim_expired_guards(&storage).await;
let expired_entries = Self::extract_expired_guards(&storage).await;
Self::release_reclaimed_guards(expired_entries);
}
});
}
@@ -991,7 +972,7 @@ mod tests {
assert!(client.acquire_lock(&request).await.expect("register shared lease").success);
requests.push(request);
}
assert_eq!(LocalClient::reclaim_expired_guards(&client.guard_storage).await, 0);
assert!(LocalClient::extract_expired_guards(&client.guard_storage).await.is_empty());
{
let registry = client.get_shard(&requests[0].lock_id).read().await;
assert_eq!(registry.entries.len(), 512);
@@ -1098,7 +1079,8 @@ mod tests {
assert_eq!(backend.get_shard(&resource).active_guard_count(), 1);
tokio::time::advance(Duration::from_secs(5)).await;
assert_eq!(LocalClient::reclaim_expired_guards(&client.guard_storage).await, 1);
let expired = LocalClient::extract_expired_guards(&client.guard_storage).await;
assert_eq!(LocalClient::release_reclaimed_guards(expired), 1);
assert_eq!(backend.get_shard(&resource).active_guard_count(), 0);
assert!(
client
@@ -1831,264 +1813,4 @@ mod tests {
.expect("second collision stamp");
assert_eq!(after.generation(), before.generation() + 1);
}
#[tokio::test(start_paused = true)]
async fn default_reaper_reclaims_expired_read_lock_without_reacquire_or_diagnostics() {
assert_eq!(DEFAULT_LEASE_REAPER_INTERVAL, Duration::from_secs(1));
assert_eq!(LocalClient::new().reaper_interval, DEFAULT_LEASE_REAPER_INTERVAL);
let manager = Arc::new(GlobalLockManager::new());
let client = LocalClient::with_manager(manager.clone());
let resource = crate::ObjectKey::new("jepsen-xpool-worm", ".rustfs-table/warehouses/default/publication.lock");
let read_req =
LockRequest::new(resource.clone(), LockType::Shared, "peer-n6").with_ttl(crate::fast_lock::DEFAULT_LOCK_TIMEOUT);
assert!(
client
.acquire_lock(&read_req)
.await
.expect("acquire default-ttl shared lock")
.success
);
let backend = manager.as_fast_lock_manager().expect("enabled physical lock backend");
tokio::time::advance(Duration::from_secs(29)).await;
tokio::task::yield_now().await;
assert_eq!(
backend.get_shard(&resource).active_guard_count(),
1,
"unexpired read lock must remain held before its 30s lease deadline"
);
// Advance just past the 30s lease plus one 1s reaper interval without calling
// list_lock_leases() or issuing any acquire on the same shard.
tokio::time::advance(Duration::from_secs(2)).await;
tokio::task::yield_now().await;
assert_eq!(
backend.get_shard(&resource).active_guard_count(),
0,
"default 1s reaper must release the physical guard within 2s after expiry"
);
assert!(
client
.check_status(&read_req.lock_id)
.await
.expect("check reaped read lock status")
.is_none()
);
let writer = manager
.acquire_lock(crate::ObjectLockRequest::new_write(resource, "writer"))
.await
.expect("conflicting writer must succeed immediately once the expired read guard is reaped");
drop(writer);
}
#[tokio::test(start_paused = true)]
async fn default_reaper_preserves_refreshed_read_lock_and_reclaims_after_extended_deadline() {
let manager = Arc::new(GlobalLockManager::new());
let client = LocalClient::with_manager(manager.clone());
let resource = crate::ObjectKey::new("jepsen-xpool-worm", "");
let read_req =
LockRequest::new(resource.clone(), LockType::Shared, "peer-n6").with_ttl(crate::fast_lock::DEFAULT_LOCK_TIMEOUT);
assert!(
client
.acquire_lock(&read_req)
.await
.expect("acquire default-ttl bucket read lock")
.success
);
let backend = manager.as_fast_lock_manager().expect("enabled physical lock backend");
tokio::time::advance(Duration::from_secs(20)).await;
assert!(
client
.refresh(&read_req.lock_id)
.await
.expect("refresh shared lease before deadline")
);
// Cross the original 30s deadline (which triggers one due-hint rescan on the shard)
// and verify the refreshed lease remains held until t=50s.
tokio::time::advance(Duration::from_secs(15)).await;
tokio::task::yield_now().await;
assert_eq!(
backend.get_shard(&resource).active_guard_count(),
1,
"refreshed read lock must survive past its original deadline"
);
assert!(
client
.check_status(&read_req.lock_id)
.await
.expect("read refreshed lease status")
.is_some()
);
tokio::time::advance(Duration::from_secs(17)).await;
tokio::task::yield_now().await;
assert_eq!(
backend.get_shard(&resource).active_guard_count(),
0,
"default 1s reaper must release the physical guard promptly after the refreshed deadline"
);
let writer = manager
.acquire_lock(crate::ObjectLockRequest::new_write(resource, "writer"))
.await
.expect("conflicting writer must succeed after the refreshed lease expires");
drop(writer);
}
#[tokio::test(start_paused = true)]
async fn reaper_releases_earlier_shard_before_waiting_on_contended_later_shard() {
let manager = Arc::new(GlobalLockManager::new());
let client = LocalClient::with_manager(manager.clone());
client.reaper_started.store(true, Ordering::Release);
let mut early_resource = None;
let mut later_resource = None;
for index in 0..4096 {
let candidate = crate::ObjectKey::new("bucket", format!("shard-order-{index}"));
let shard_idx = client.get_resource_shard_index(&candidate);
if shard_idx == 0 && early_resource.is_none() {
early_resource = Some(candidate);
} else if shard_idx > 0 && later_resource.is_none() {
later_resource = Some(candidate);
}
if early_resource.is_some() && later_resource.is_some() {
break;
}
}
let early_resource = early_resource.expect("find resource hashed to shard 0");
let later_resource = later_resource.expect("find resource hashed to a later shard");
let later_shard_idx = client.get_resource_shard_index(&later_resource);
let early_req =
LockRequest::new(early_resource.clone(), LockType::Shared, "owner-early").with_ttl(Duration::from_secs(5));
let later_req =
LockRequest::new(later_resource.clone(), LockType::Shared, "owner-later").with_ttl(Duration::from_secs(5));
assert!(
client
.acquire_lock(&early_req)
.await
.expect("acquire early shard lock")
.success
);
assert!(
client
.acquire_lock(&later_req)
.await
.expect("acquire later shard lock")
.success
);
tokio::time::advance(Duration::from_secs(5)).await;
let (release_later, later_owner) = hold_guard_shard(client.guard_storage[later_shard_idx].clone());
let mut sweep = Box::pin(LocalClient::reclaim_expired_guards(&client.guard_storage));
assert!(
matches!(futures::poll!(&mut sweep), Poll::Pending),
"sweep must pause while the later shard is contended"
);
let backend = manager.as_fast_lock_manager().expect("enabled physical lock backend");
assert_eq!(
backend.get_shard(&early_resource).active_guard_count(),
0,
"expired physical guard from earlier shard must already be released outside the shard lock"
);
let writer = manager
.acquire_lock(crate::ObjectLockRequest::new_write(early_resource, "writer"))
.await
.expect("writer on earlier shard must not be blocked by later shard contention");
drop(writer);
release_later.send(()).expect("release contended later shard");
later_owner.join().expect("later shard owner must finish");
assert_eq!(sweep.await, 2);
assert_eq!(backend.get_shard(&later_resource).active_guard_count(), 0);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn default_reaper_reclaims_expired_read_lock_under_hot_shard_contention_within_budget() {
let manager = Arc::new(GlobalLockManager::new());
let client = Arc::new(LocalClient::with_manager(manager.clone()));
let backend = manager.as_fast_lock_manager().expect("enabled physical lock backend");
let expired_resource = crate::ObjectKey::new("jepsen-xpool-worm", "expired-hot-target");
let hot_shard = client.get_resource_shard_index(&expired_resource);
let contending_resource = (0..4096)
.map(|index| crate::ObjectKey::new("jepsen-xpool-worm", format!("hot-peer-{index}")))
.find(|candidate| {
candidate != &expired_resource
&& client.get_resource_shard_index(candidate) == hot_shard
&& !Arc::ptr_eq(backend.get_shard(candidate), backend.get_shard(&expired_resource))
})
.expect("find sibling resource sharing the hot guard shard on a distinct backend shard");
// Pre-register sibling leases on the same guard shard and continuously refresh/inspect
// them. Unlike acquire_lock(), refresh() contends on the shard write lock without running
// eager reclaim, so only the background 1s reaper can release `expired_resource`.
let mut sibling_ids = Vec::with_capacity(8);
for worker_idx in 0..8 {
let req = LockRequest::new(contending_resource.clone(), LockType::Shared, format!("hot-{worker_idx}"))
.with_ttl(Duration::from_secs(30));
assert!(
client
.acquire_lock(&req)
.await
.expect("register contending sibling read lock")
.success
);
sibling_ids.push(req.lock_id);
}
let stop = Arc::new(AtomicBool::new(false));
let mut workers = tokio::task::JoinSet::new();
for lock_id in sibling_ids.clone() {
let client = client.clone();
let stop = stop.clone();
workers.spawn(async move {
while !stop.load(Ordering::Relaxed) {
assert!(client.refresh(&lock_id).await.expect("hot worker refresh"));
let _ = client.check_status(&lock_id).await.expect("hot worker status");
tokio::task::yield_now().await;
}
});
}
let ttl = Duration::from_millis(100);
let expired_req = LockRequest::new(expired_resource.clone(), LockType::Shared, "peer-n6").with_ttl(ttl);
let acquired_at = Instant::now();
assert!(
client
.acquire_lock(&expired_req)
.await
.expect("acquire target read lock on hot shard")
.success
);
let expiry_at = acquired_at + ttl;
let deadline = expiry_at + Duration::from_secs(3);
while backend.get_lock_info(&expired_resource).is_some() {
assert!(
Instant::now() < deadline,
"default 1s reaper failed to release expired read guard within 3s under hot-shard contention"
);
tokio::time::sleep(Duration::from_millis(20)).await;
}
assert_eq!(backend.get_shard(&expired_resource).active_guard_count(), 0);
let writer = manager
.acquire_lock(crate::ObjectLockRequest::new_write(expired_resource, "writer"))
.await
.expect("writer must succeed once the expired read guard is physically released");
drop(writer);
stop.store(true, Ordering::Relaxed);
while let Some(joined) = workers.join_next().await {
joined.expect("hot-shard worker must exit cleanly");
}
for lock_id in sibling_ids {
assert!(client.release(&lock_id).await.expect("release contending sibling read lock"));
}
assert_eq!(backend.get_shard(&contending_resource).active_guard_count(), 0);
}
}
+5 -8
View File
@@ -1841,19 +1841,16 @@ where
}
RemoteScannerFrameResult::DurableProgress(receipt) => {
let actual = receipt.identity.tier_registry_generation;
let expected_identity = crate::DataUsageScanIdentity {
tier_registry_generation: expected.tier_registry_generation,
..receipt.identity
};
if !(expected.supports_durable_progress || expected.supports_complete_observation)
|| (!expected.supports_durable_progress && receipt.advanced)
|| (!expected.supports_complete_observation && receipt.observation.is_some())
|| frame.phase != RemoteScannerPhase::Persisting
|| receipt.source != expected.source
|| expected.checkpoint_identity.is_none_or(|identity| {
// The worker fences persistence with its own process-local epoch.
crate::DataUsageScanIdentity {
publication_epoch: identity.publication_epoch,
tier_registry_generation: expected.tier_registry_generation,
..receipt.identity
} != identity
})
|| Some(expected_identity) != expected.checkpoint_identity
|| receipt.scan_plan_digest != expected.scan_plan_digest
|| receipt.checkpoint_plan_digest != expected.checkpoint_plan_digest
|| receipt.leader_epoch != expected.leader_epoch
@@ -43,20 +43,13 @@ fn durable_receipt() -> RemoteScannerDurableProgress {
#[tokio::test]
async fn durable_progress_requires_negotiation_exact_scope_mac_and_eof() {
let leader_publication_epoch = 3;
assert_ne!(progress_identity().publication_epoch, leader_publication_epoch);
for case in [
"valid",
"progress_only",
"generation",
"after_preflight",
"legacy",
"source",
"identity",
"layout",
"mode",
"missing_identity",
"observation_epoch",
"epoch",
"plan",
"future_observation",
@@ -68,13 +61,16 @@ async fn durable_progress_requires_negotiation_exact_scope_mac_and_eof() {
let writer_auth = FrameAuthenticator::for_test(request_id);
let reader_auth = FrameAuthenticator::for_test(if case == "mac" { Uuid::new_v4() } else { request_id });
let mut receipt = durable_receipt();
if case != "valid" {
receipt.identity.tier_registry_generation = 1;
receipt.observation.as_mut().expect("fixture observation").identity = receipt.identity;
}
match case {
"generation" | "after_preflight" => receipt.identity.tier_registry_generation = 1,
"progress_only" => receipt.observation = None,
"source" => receipt.source = DataUsageCacheSource::new(99, 99),
"identity" => receipt.identity.bucket_incarnation = Uuid::from_u128(99),
"layout" => receipt.identity.set_layout = DataUsageScanPlanDigest([99; 32]),
"mode" => receipt.identity.scan_mode = HealScanMode::Deep,
"identity" => {
receipt.identity.bucket_incarnation = Uuid::from_u128(99);
receipt.observation.as_mut().expect("fixture observation").identity = receipt.identity;
}
"epoch" => receipt.leader_epoch += 1,
"plan" => receipt.checkpoint_plan_digest = DataUsageScanPlanDigest([99; 32]),
"future_observation" => receipt.observation.as_mut().expect("fixture observation").completed_cycle += 1,
@@ -85,12 +81,6 @@ async fn durable_progress_requires_negotiation_exact_scope_mac_and_eof() {
}
_ => {}
}
if let Some(observation) = receipt.observation.as_mut() {
observation.identity = receipt.identity;
if case == "observation_epoch" {
observation.identity.publication_epoch += 1;
}
}
let mut bytes = Vec::new();
write_frame(
&mut bytes,
@@ -123,16 +113,13 @@ async fn durable_progress_requires_negotiation_exact_scope_mac_and_eof() {
tier_registry_generation: 0,
supports_durable_progress: case != "legacy",
supports_complete_observation: case != "legacy",
checkpoint_identity: (case != "missing_identity").then(|| crate::DataUsageScanIdentity {
publication_epoch: leader_publication_epoch,
..progress_identity()
}),
checkpoint_identity: Some(progress_identity()),
},
reader_auth,
Instant::now() + Duration::from_secs(5),
)
.await;
if matches!(case, "valid" | "progress_only") {
if case == "valid" {
let RemoteScannerOutcome::DurableProgress {
advanced, observation, ..
} = result.expect("validated progress")
@@ -140,13 +127,7 @@ async fn durable_progress_requires_negotiation_exact_scope_mac_and_eof() {
panic!("progress cannot become Complete")
};
assert!(advanced);
if case == "valid" {
let observation = observation.expect("preserved companion");
assert_eq!(observation.identity, progress_identity());
assert_eq!(observation.entry.objects, 5);
} else {
assert!(observation.is_none());
}
assert_eq!(observation.expect("preserved companion").entry.objects, 5);
} else if case == "generation" {
assert!(matches!(
result,
@@ -156,20 +137,6 @@ async fn durable_progress_requires_negotiation_exact_scope_mac_and_eof() {
assert!(result.is_err(), "invalid progress case {case}");
}
}
println!(
"usage_assertion: {}",
serde_json::json!({
"case_id": "USAGE-23", "assertion_id": "USAGE-23-A01", "status": "PASS",
"evidence": {
"worker_publication_epoch": progress_identity().publication_epoch,
"leader_publication_epoch": leader_publication_epoch,
"outcome": "durable_progress",
"companion_identity_preserved": true,
"mismatched_companion_rejected": true,
}
}),
);
println!("usage_cleanup: {}", serde_json::json!({"case_id": "USAGE-23", "status": "PASS"}));
}
#[test]
+1 -74
View File
@@ -192,7 +192,7 @@ pub struct LockEntry {
pub since: Option<String>,
/// How long the lock has been held, in seconds.
pub elapsed_secs: u64,
/// Truncated whole seconds remaining until the lock's timeout expires (`0` when under 1s remains or already past).
/// Seconds until the lock's timeout expires (0 if already past).
pub ttl_secs: u64,
}
@@ -1820,77 +1820,4 @@ mod tests {
assert!(client.release(&lock_id).await.expect("local lock release should succeed"));
}
#[tokio::test(start_paused = true)]
async fn collect_top_locks_is_read_only_and_reports_truncated_remaining_ttl() {
use rustfs_lock::{FastObjectLockManager, GlobalLockManager, LocalClient, LockClient, LockRequest, LockStatus};
let manager = Arc::new(GlobalLockManager::Enabled(Arc::new(FastObjectLockManager::new())));
let client = Arc::new(LocalClient::with_manager(manager.clone()));
let resource = ObjectKey::new("diag-bucket", "subsecond-read-lock");
// Half-second offset puts expiry between the t=30s and t=31s 1s reaper ticks.
let request = LockRequest::new(resource.clone(), LockType::Shared, "peer-n6").with_ttl(Duration::from_millis(30_500));
assert!(
client
.acquire_lock(&request)
.await
.expect("shared lock acquisition should succeed")
.success
);
// Let the lazily spawned 1s reaper initialize its interval at t=0 before advancing virtual time.
tokio::task::yield_now().await;
let clients: Vec<Arc<dyn rustfs_lock::client::LockClient>> = vec![client.clone()];
// At t=29.6s, 900ms remains: truncated ttl_secs is 0 while the guard is still live.
tokio::time::advance(Duration::from_millis(29_600)).await;
tokio::task::yield_now().await;
let subsecond = collect_top_locks_with_clients(TOP_LOCKS_DEFAULT_LIMIT, manager.clone(), clients.clone()).await;
let entry = subsecond
.locks
.iter()
.find(|entry| entry.bucket == "diag-bucket" && entry.object == "subsecond-read-lock")
.expect("sub-second live read lock must remain visible");
assert_eq!(entry.lock_type, "READ");
assert_eq!(entry.ttl_secs, 0, "remaining TTL under 1s truncates to 0");
assert_eq!(
client
.check_status(&request.lock_id)
.await
.expect("read live lock status")
.expect("live guard remains registered")
.status,
LockStatus::Acquired
);
// Step through the t=30.0s tick while the lease is still live (deadline is t=30.5s),
// then move to t=30.6s: the lease is expired, while the next 1s reaper tick is at t=31.0s.
// Calling top/locks must remain read-only and keep reporting the still-held physical guard.
tokio::time::advance(Duration::from_millis(400)).await;
tokio::task::yield_now().await;
tokio::time::advance(Duration::from_millis(600)).await;
tokio::task::yield_now().await;
let before_reap = collect_top_locks_with_clients(TOP_LOCKS_DEFAULT_LIMIT, manager.clone(), clients.clone()).await;
let expired_entry = before_reap
.locks
.iter()
.find(|entry| entry.bucket == "diag-bucket" && entry.object == "subsecond-read-lock")
.expect("unreaped physical guard must remain visible to read-only top/locks");
assert_eq!(expired_entry.ttl_secs, 0);
assert_eq!(
client
.check_status(&request.lock_id)
.await
.expect("read expired lock status")
.expect("top/locks must not mutate or release an unreaped guard")
.status,
LockStatus::Expired
);
// After the t=31.0s reaper tick runs, the background reaper frees the guard on its own.
tokio::time::advance(Duration::from_millis(500)).await;
tokio::task::yield_now().await;
let after_reap = collect_top_locks_with_clients(TOP_LOCKS_DEFAULT_LIMIT, manager, clients).await;
assert!(after_reap.locks.is_empty(), "expired read lock must disappear after background reaping");
}
}